Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

So, I'm using a script I've made to convert videos to the webm format. A certain program calls the script, sending %f which is the full, absolute file name of the video, like this:

converter.sh %f

where %f has two possible extensions, .avi or .mpg.

# /bin/bash
ffmpeg -i $1 `dirname $1``basename $1 avi`webm && rm $1

It currently works perfectly when $1 contains a .avi file, because basename removes the .avi extension. When $1 ends with .mpg instead, the result is .mpgwebm.

How can I modify that script to be able to receive those two possible different formats?


Resuming: If $1 is /somedir/video.avi, the script should do:

ffmpeg -i /somedir/video.avi /somedir/video.webm

And if $1 is /somedir/video.mpg, the script should do:

ffmpeg -i /somedir/video.mpg /somedir/video.webm

I know this might be fool for some people, but I'm kind of new with the bash.

share|improve this question

1 Answer 1

up vote 7 down vote accepted

You can use substitution mechanisms provided by most shells:

B=$(basename "$1"); D=$(dirname "$1");
ffmpeg -i "$1" "$D/${B%.*}.webm" && rm "$1"

In fact, basename and dirname could also be emulated by substitutions.

Note: direct .* suffix removal is not correct on paths like this.dir/file.

share|improve this answer
1  
I allowed myself to quote the variable and to replace backquotes by $(…) –  Stéphane Gimenez Aug 15 '11 at 3:58
    
Yes, but the files would be named *.avi.webm or *.mpg.webm because basename doesn't remove the extension unless you specify it after. –  Tomas Aug 15 '11 at 4:01
    
Sorry, my first answer was stupid! Edited and still need improvement. –  Stéphane Gimenez Aug 15 '11 at 4:06
2  
@Tomas: Without quotes and in the case your filenames contain spaces, they would be split into several paths. –  Stéphane Gimenez Aug 15 '11 at 4:27
2  
Why use dirname, basename and not to use directly `ffmpeg -i "$1" "${1%.*}.webm" && rm "$1" –  enzotib Aug 15 '11 at 8:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.