How can I traverse a directory tree using a bash or Perl script? How can I traverse a directory tree using a bash or Perl script? unix unix

How can I traverse a directory tree using a bash or Perl script?


find . -type f -print0 | xargs -0 grep -l -E 'some_regexp' > /tmp/list.of.files

Important parts:

  • -type f makes the find list only files
  • -print0 prints the files separated not by \n but by \0 - it is here to make sure it will work in case you have files with spaces in their names
  • xargs -0 - splits input on \0, and passes each element as argument to the command you provided (grep in this example)

The cool thing with using xargs is, that if your directory contains really a lot of files, you can speed up the process by paralleling it:

find . -type f -print0 | xargs -0 -P 5 -L 100 grep -l -E 'some_regexp' > /tmp/list.of.files

This will run the grep command in 5 separate copies, each scanning another set of up to 100 files


use find and grep

find . -exec grep -l -e 'myregex' {} \; >> outfile.txt

-l on the grep gets just the file name

-e on the grep specifies a regex

{} places each file found by the find command on the end of the grep command

>> outfile.txt appends to the text file


grep -l -R <regex> <location> should do the job.