Richo Richo - 1 year ago 34
Bash Question

Use lines in a file as filenames for grep?

I have a file which contains filenames (and the full path to them) and I want to search for a word within all of them.
some pseudo-code to explain:

grep keyword <all files specified in files.txt>


cat files.txt > grep keyword
cat files txt | grep keyword

the problem is that I can only get grep to search the filenames, not the contents of the actual files.

cat files.txt | xargs grep keyword


grep keyword `cat files.txt`

or (equivalent to previous but harder to mis-read)

grep keyword $(cat files.txt)

should do the trick.


  • If files.txt contains file names with spaces, either solution will malfunction, because "This is a filename.txt" will be interpreted as four files, "This", "is", "a", and "filename.txt". A good reason why you shouldn't have spaces in your filenames, ever.

    • There are ways around this, but none of them is trivial. (find ... -print0 / xargs -0 is one of them.)
  • The second (cat) version can result in a very long command line (which might fail when exceeding the limits of your environment). The first (xargs) version handles long input automatically; xargs offers several options to control the details.