Luke Oliff.

TIL: Batch File Operations With find -exec

·TIL·1 min read·Luke Oliff

Rename a hundred files. Convert a directory of WAVs to MP3. Move every log file older than a day. find -exec handles all of it without a for loop.

find . -name "*.wav" -exec ffmpeg -i {} {}.mp3 \;

find finds every .wav file. -exec runs ffmpeg on each one. {} is replaced by the filename. The escaped semicolon marks the end of the exec command.

find . -name "*.bak" -exec rm {} \;

Delete every .bak file across the entire project tree.

find . -name "*.tmp" -exec mv {} /tmp/archive/ \;

Move matching files to a different directory. The full path is available inside the exec command.

What is the difference between -exec and a for loop?

-exec is safer with unusual filenames (spaces, newlines). Use -exec with + instead of ; to batch files into a single command invocation for better performance.