linux – Loop over file names from `find`?

Loop over file names from `find`? & execute a command

Some examples…

find . -name '*.mp3' -exec cmd {} \;

or

find . -name '*.mp3' -print0 | xargs -0 cmd

While Loop

As others have pointed out, you can frequently use a while read loop to read filenames line by line, it has the drawback of not allowing line-ends in filenames (who uses that?).

xargs vs. -exec cmd {} +

Summarizing the comments saying that -exec+ is better, I prefer xargs because it is more versatile:

  • works with other commands than just find
  • allows ‘batching’ (grouping) in command lines, say xargs -n 10 (ten at a time)
  • allows parallellizing, say xargs -P4 (max 4 concurrent processes running at a time)
  • does privilige separation (such as in the OP’s case, where he uses sudo find: using -exec would run all commands as the root user, whereas with xargs that isn’t necessary:
    sudo find -name '*.mp3' -print0 | sudo xargs -0 require_root.sh
    sudo find -name '*.mp3' -print0 | xargs -0 nonroot.sh
  • in general, pipes are just more versatile (logging, sorting, remoting, caching, checking, parallelizing etc, you can do that)

Source : linux – Loop over file names from `find`? – Stack Overflow