7

I have a text file containing names (nameslist.txt) and I want to read them using cat and pipe the result with xargs to a grep command, so that grep checks the existence of each name that it receives in a target file (targetfile.txt).

Let's say targetfile.txt contains a large number of names which might have some of those names in nameslist.txt.

What should I add between xargs and grep, and between grep and ./targetfile.txt, below?

cat ./nameslist.txt | xargs grep ./targetfile.txt

Thank you

  • 2
    Assuming one name per line, you don't need xargs here - grep can read a list of patterns (or fixed strings, with the -F option) from a file: grep -F -f nameslist.txt ./targetfile.txt – steeldriver Jan 14 at 2:28
8

You can use -I to tell xargs to use a particular character or sequence of characters as a placeholder for the argument. From man xargs:

   -I replace-str
          Replace occurrences of replace-str in the initial-arguments with
          names read from standard input.  Also, unquoted  blanks  do  not
          terminate  input  items;  instead  the  separator is the newline
          character.  Implies -x and -L 1.

A common choice is {} so

cat nameslist.txt | xargs -I {} grep {} targetfile.txt

or (without the useless use of cat)

< nameslist.txt xargs -I {} grep {} targetfile.txt

However, assuming your list has one name per line you don't need xargs here at all - grep can read a list of patterns (or fixed strings, with the -F option) from a file:

grep -F -f nameslist.txt targetfile.txt
  • Thank you so much. 100% what I was looking for. Pretty informative. – arash deilami Jan 14 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.