Monday, April 27, 2009

for loop using 'find'

I find myself constantly creating complex loops and forgetting, for a small instance of time, how to construct them again.

In this case, I wanted to list files that passed a certain criteria and loop over them so that I could call a Perl script on them.

For example:

for i in `find . -type f -name '*.pm' -print`; \
do perl some_script.pl $i; \
done
In the above case, I am searching for all files that end in pm, starting from the current directory (.) and once found, I am executing the perl script some_script.pl on them.

Of course, you don't have run a perl script ... you could just echo the output:

for i in `find . -type f -name '*.pm' -print`; \
do echo found $i; \
done
Now, next time I need to run a similar command, I wont forget how to construct the query!

1 comment:

Ed said...

another for loop (one line):

for i in $(ls); do echo some file $i; donebasically, in the
   do ...;
part do whatever you want ... call a perl script, move the file, etc ... of course, you are not limited to ls in the $(ls) bit either!