7

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.

1 Answer 1

9

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.

10
  • 1
    I allowed myself to quote the variable and to replace backquotes by $(…) Aug 15, 2011 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, 2011 at 4:01
  • Sorry, my first answer was stupid! Edited and still need improvement. Aug 15, 2011 at 4:06
  • 2
    @Tomas: Without quotes and in the case your filenames contain spaces, they would be split into several paths. Aug 15, 2011 at 4:27
  • 2
    Why use dirname, basename and not to use directly `ffmpeg -i "$1" "${1%.*}.webm" && rm "$1"
    – enzotib
    Aug 15, 2011 at 8:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .