ronald mcd
ronald mcd

Reputation: 33

How to perform multiple commands for each file I find

So I am searching for files in a specific directory and for each file I find I want to perform a bunch of the same commands on these files.

I search for these files with this find command:

Upvotes: 3

Views: 1221

Answers (1)

Rakesh Gupta
Rakesh Gupta

Reputation: 3760

While loop is your friend then

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

If you are 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 command above _val is used instead of {} to avoid unnecessary quoting (inspired by)

Upvotes: 3

Related Questions