Ubuntu – How to pass list of names to be searched by grep using xargs

command linegreptext processingxargs

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

Best Answer

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