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

0

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?

usr122212

Posted 2013-01-22T16:58:08.800

Reputation: 103

Answers

5

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

terdon

Posted 2013-01-22T16:58:08.800

Reputation: 45 216

after running the above, i get this: ce_002.mp4: unknown primary or operator am i doing something wrong here? – usr122212 – 2013-01-22T17:17:49.980

Well, the only thing I can think of is that your file names contain weird characters... Try the updated answer. – terdon – 2013-01-22T17:23:28.200

thanks for your updated answer! works great. I should read more up on exec :). – usr122212 – 2013-01-22T17:26:18.387

2I made a few corrections. The globbing pattern in -name should always be quoted. Otherwise the * glob will be expanded before find even sees it. This means the command would fail if you were searching in another directory than the current one, or going deeper than one level. Also, the -exec option deals with any kind of filename. Using xargs is not really necessary—the while loop works better, but here the output should be null-delimited. – slhck – 2013-01-22T17:55:20.930

thanks for your edit and details, this works flawlessly! – usr122212 – 2013-01-22T20:14:39.427