在Linux上用作grep搜索规范的管道输出

在Linux上用作grep搜索规范的管道输出,linux,grep,Linux,Grep,如何通过管道将grep的输出作为另一个grep的搜索模式 例如: grep <Search_term> <file1> | xargs grep <file2> grep | xargs grep 我想要第一个grep的输出作为第二个grep的搜索词。上面的命令将第一个grep的输出视为第二个grep的文件名。我尝试对第二个grep使用-e选项,但也不起作用。如果使用Bash,则可以使用反勾号: > grep -e "`grep ... ...`"

如何通过管道将grep的输出作为另一个grep的搜索模式

例如:

grep <Search_term> <file1> | xargs grep <file2>
grep | xargs grep

我想要第一个grep的输出作为第二个grep的搜索词。上面的命令将第一个grep的输出视为第二个grep的文件名。我尝试对第二个grep使用
-e
选项,但也不起作用。

如果使用Bash,则可以使用反勾号:

> grep -e "`grep ... ...`" files
-e
标志和双引号用于确保以连字符开头的初始
grep
的任何输出不会被解释为第二个
grep
的选项

请注意,双引号技巧(它还确保grep的输出被视为单个参数)仅适用于Bash。它似乎与(t)csh不起作用

还要注意,反勾号是将一个程序的输出输入另一个程序的参数列表的标准方式。并非所有程序都能像(f)grep那样方便地从stdin读取参数。

试试看

grep ... | fgrep -f - file1 file2 ...

您需要使用
xargs
-i
开关:

grep ... | xargs -ifoo grep foo file_in_which_to_search
这将采用
-i
之后的选项(在本例中为
foo
),并用第一个
grep
的输出替换命令中出现的每个选项

这与:

grep `grep ...` file_in_which_to_search

我发现下面的命令使用$()工作,我的第一个命令在括号内,让shell首先执行它

grep $(dig +short) file

当给我一个主机名时,我用它在文件中查找IP地址。

我想在文件中搜索文本(使用grep),这些文件在当前目录中的文件名中有某种模式(使用find查找)。我使用了以下命令:

 grep -i "pattern1" $(find . -name "pattern2")
这里pattern2是文件名中的模式,pattern1是搜索到的模式 在匹配模式2的文件中


编辑:不是严格意义上的管道,但仍然相关且非常有用…

这是我用来从列表中搜索文件的方法:

ls -la | grep 'file-in-which-to-search'

好吧,打破规则,因为这不是一个答案,只是一个注意,我不能得到这些解决方案的任何工作

% fgrep -f test file
很好

% cat test | fgrep -f - file
fgrep: -: No such file or directory
失败了

% cat test | xargs -ifoo grep foo file 
xargs: illegal option -- i
usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]
             [-L number] [-n number [-x]] [-P maxprocs] [-s size]
             [utility [argument ...]]
失败了。请注意,大写字母I是必需的。如果我用它,一切都好

% grep "`cat test`" file
其工作原理是,它为匹配的术语返回一行,但也为未找到匹配项的每个文件返回一行
grep:test:No这样的文件或目录中的第3行


是我遗漏了什么,还是这只是我的Darwin发行版或bash shell中的差异?

我尝试了这种方法,效果非常好

[opuser@vjmachine abc]$ cat a
not problem
all
problem
first
not to get
read problem
read not problem

[opuser@vjmachine abc]$ cat b
not problem xxy
problem abcd
read problem werwer
read not problem  98989
123 not problem 345
345 problem tyu

[opuser@vjmachine abc]$ grep -e "`grep problem a`" b --col
not problem xxy
problem abcd
read problem werwer
read not problem  98989
123 not problem 345
345 problem tyu

[opuser@vjmachine abc]$ 

您应该以这种方式grep,要仅提取文件名,请参阅参数-l(小写字母l):

因为在简单的grep上,输出的信息要比文件名多得多。例如,当你这样做的时候

grep someSearch *
您将像这样通过管道发送到xargs信息

filename1: blablabla someSearch blablabla something else
filename2: bla someSearch bla otherSearch
...
将上述任何一条管线输送到xargs都是毫无意义的。 但当您执行grep-l someSearch*时,您的输出将如下所示:

filename1
filename2

这样的输出现在可以传递给xargs

它使用第一个grep的输出作为第二个grep的grep模式,正如问题所问的那样。@Nathan,它使用第一个grep的输出作为fgrep模式的输入文件。“-f-”是告诉unix程序使用标准输入作为输入文件(如果它通常使用输入文件)的正常方式。传统上,fgrep是唯一一个将文件作为输入的grep,尽管Gnu可能已经修改了其他grep。。。我错过了单机版“
-
”。谢谢如果第一个grep返回多个结果,这个可能会有问题。我尝试了这个解决方案,它很有效。谢谢提供。相关:xargs replstr选项在OSX上使用大写-I
filename1
filename2