Jan 19

Bash scripting oneliner: call a script on each file from a file glob

Category: Linux   — Published by goeszen on January 19, 2016 at 5:10 pm

So, how do you
... call a script on each file from a file glob / wilcard selection pattern?
... call a script on each file in a dir with a bash script one liner?
... call a script for each / foreach file in a dir?
... do something for each file from a file glob ?
... do something on a file glob?

In terminal, in shell, in bash, on the command-line?

Where "script" can actually be some binary / program, or whatever.

Answer / example:

for f in *.mp4; do avconv -i "$f" -acodec copy -vn "out/$f"; done

Here we select every .mp4 file in current directory, and run avconv on it, extracting the audio stream while discarding the video. The resulting file is written in a sub-dir (which we mkdir before), so we don't clobber the source file, and so we don't have to deal with renaming the basename/filename.
You need to put quotes around $f for files with spaces.

Another approach is to use the find command for that. Via the -exec and -execdir switches, it is able to execute some command on each found file. The -name switch accepts a file glob like -name "*.mp4" for such globbing. See OptiJPEG – how to optimize JPG images losslessly for an example.

Related: Linux command: find files and run command on them

Leave a Reply

=