How can I run a command on every file in a given directory?

Posted on

Problem :

I am using mp4box to move the MOOV atoms on MP4 files.

The thing is, I will have 6 files in a given folder and I don’t want to run the inter 500 command six separate times.

Is it possible to do something like mp4box -inter 500 * in a directory to have the command run on all the mp4 files in that folder?

Solution :

You can use the -exec option of find. Here, '{}' is replaced with the file name of every MP4 file. This will deal with all kinds of file names, even those containing spaces or newlines. You need to supply -maxdepth 1 to only search the current directory.

find . -iname "*.mp4" -maxdepth 1 -exec mp4box -inter 500 '{}' ;

An alternative, more convoluted way would involve piping the output from find into a loop with read. Here, every file is delimited by the NUL character, and you need to tell read to split the input on this character, which is achieved by -d ''. You also need to quote the variable "$file", so spaces or globbing characters in the name are retained.

find . -iname "*.mp4" -maxdepth 1 -print0 | while IFS= read -d '' -r file; do mp4box -inter 500 "$file"; done

Leave a Reply

Your email address will not be published. Required fields are marked *