How to pass list of names to be searched by grep using xargs?
Solution 1:
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