如何使用xargs将姓名列表传递给grep进行搜索?

我有一个包含姓名的文本文件(nameslist.txt),我想使用cat命令读取它们,并使用xargs将结果传递给grep命令,使得grep命令可以在目标文件(targetfile.txt)中检查接收到的每个姓名是否存在。
假设targetfile.txt包含大量可能在nameslist.txt中出现的姓名。
请问,在xargs和grep之间以及grep和./targetfile.txt之间,我应该添加什么?
cat ./nameslist.txt | xargs grep ./targetfile.txt

谢谢


2假设每行一个名称,你在这里不需要使用xargs - grep可以从文件中读取模式列表(或固定字符串,使用-F选项):grep -F -f nameslist.txt ./targetfile.txt - steeldriver
1个回答

您可以使用-I来告诉xargs使用特定字符或字符序列作为参数的占位符。来自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.

常见选择是{}所以

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

或者(不用无用地使用cat)
< nameslist.txt xargs -I {} grep {} targetfile.txt

然而,假设您的列表每行只有一个名称,您根本不需要在这里使用xargs - grep可以从文件中读取一系列模式(或固定字符串,使用-F选项)。
grep -F -f nameslist.txt targetfile.txt

非常感谢。百分之百符合我所期待的。非常有信息量。 - arash deilami