Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use lines in a file as filenames for grep?

Tags:

grep

shell

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>

or

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.

like image 661
Richo Avatar asked Dec 06 '25 05:12

Richo


2 Answers

cat files.txt | xargs grep keyword

or

grep keyword `cat files.txt`

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

grep keyword $(cat files.txt)

should do the trick.

Pitfalls:

  • 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.

like image 88
DevSolar Avatar answered Dec 07 '25 19:12

DevSolar


Both of the answers from DevSolar work (tested on Linux Ubuntu), but the xargs version is preferable if there may be many files, since it will avoid running into command line length limits.

so:

cat files.txt | xargs grep keyword

is the way to go

like image 41
Malcolm Box Avatar answered Dec 07 '25 20:12

Malcolm Box



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!