Use lines in file as file names for grep?

I have a file that contains file names (and the full path to them), and I want to search for a word in 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 for file names, not for the contents of actual files.

+3
source share
5 answers
cat files.txt | xargs grep keyword

or

grep keyword `cat files.txt`

or (equivalent to the previous one, but more difficult to read incorrectly)

grep keyword $(cat files.txt)

gotta do the trick.

Traps:

  • .txt , , " .txt" , "This", "is", "a" "filename.txt". , , -.

    • , . (... -print0/xargs -0 .)
  • (cat) ( ). (xargs) ; xargs .

+7

DevSolar ( Linux Ubuntu), xargs , , .

:

cat files.txt | xargs grep keyword

-

+2
tr '\n' '\0' <files.txt | LANG=C xargs -r0 grep -F keyword
  • tr NUL, ( -0 xargs).
  • xargs -r grep "" , - grep-, .
  • LANG = C ,
  • grep -F , .
+2

bash, ksh zsh :

grep keyword $(<files.txt)
0

For a long time, when the latter created a bash script shell, but you could save the result of the first grep (the one that found all the file names) in the array and iterate over it, issuing even more grep commands.

A good starting point should be a bash writing guide.

-2
source

Source: https://habr.com/ru/post/1705456/


All Articles