将 xargs 与 cat 和 grep 结合

问题描述

我想从文件获取输出,并将其作为我要执行的同一文件上的 grep 命令的参数提供:

:~$ cat example
cat
dog
mouse
ant

:~$ cat example | xargs cat example | grep
Usage: grep [OPTION]... PATTERN [FILE]...
cat: cat: No such file or directory
cat: dog: No such file or directory
cat: mouse: No such file or directory
cat: antTry 'grep --help' for more @R_292_4045@ion.
: No such file or directory

换句话说,预期的命令是:

cat example | grep cat
cat example | grep dog
cat example | grep mouse
cat example | grep ant

解决方法

您需要像这样将 cat example 的输出提供给 xargs -I{},其中 {} 是参数占位符:

cat example | xargs -n1 -I{} grep {} example