Bash 将xargs与cat和grep相结合

Bash 将xargs与cat和grep相结合,bash,shell,command,cat,xargs,Bash,Shell,Command,Cat,Xargs,我希望从文件中获取输出,并将其作为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

我希望从文件中获取输出,并将其作为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 information.
: 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

重点到底是什么?假设文件中没有重复项,并且行中不包含任何regex元字符,则您希望管道生成的输出将与初始
cat
命令的输出相同。我有一个包含主机名的文件。每个主机名都有一个“开始”和一个“结束”。主机名1:开始。主机名以随机顺序显示,因此您不会看到hostname1:START和下一行hostname1:FINISH。它很可能与其他主机名22:START或主机名33:FINISH混合使用。等等,我只是想先;提取主机名部分“cat-example | cut-d”:“f 1”。第二在对同一文件进行分类时,将主机名作为grep参数输入,以便输出按顺序显示:hostname1:START(\n)hostname1:FINISH(\n)hostname2:START(\n)hostname2:FINISH。等等。您现在描述的问题与问题中提出的问题明显不同。它需要一种与这里提出的解决方案截然不同的方法。我不确定这是否符合OP的要求。他们很容易重新组织命令,然后他们会考虑把它一直缩写为<代码> CAT示例< /代码>。这不是100%等价的,但在示例中它将产生相同的输出。如果他们不准备进行这么多的重组,那么他们也可能不会像这个答案中所建议的那样准备这么多。@JohnBollinger谢谢你,我同意。OP应在顶部回应您的评论并澄清。