Linux – How to execute multiple commands for each file I find

How to execute multiple commands for each file I find… here is a solution to the problem.

How to execute multiple commands for each file I find

So I search for files

in a specific directory, and for each file I find, I want to execute the same series of commands on those files.

I searched for these files using this find command :

Solution

The while loop is your friend

find . -maxdepth 1 -type f -name "file*" | while read file; do
   echo $file;
   # perform other operations on $file here
done

If you’re not a friend of the while loop

$ ls -1 file*
file.txt
file1.txt

$ find . -maxdepth 1 -type f -name "file*" | xargs -n1 -I_val -- sh -c 'echo command1_val; echo command2_val'
command1./file.txt
command2./file.txt
command1./file1.txt
command2./file1.txt

In the above command, use _val instead of {} to avoid unnecessary references (inspired by)

).

Related Problems and Solutions