30

如何将 grep 的输出作为另一个 grep 的搜索模式进行管道传输?

举个例子:

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

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

4

9 回答 9

19

您需要使用xargs's-i开关:

grep ... | xargs -ifoo grep foo file_in_which_to_search

这采用 after -i(foo在这种情况下) 的选项,并将命令中每次出现的它替换为 first 的输出grep

这与以下内容相同:

grep `grep ...` file_in_which_to_search
于 2009-10-21T11:27:41.640 回答
13

尝试

grep ... | fgrep -f - file1 file2 ...
于 2009-01-12T23:52:23.300 回答
10

如果使用 Bash,那么您可以使用反引号:

> grep -e "`grep ... ...`" files

标志和双引号的-e存在是为了确保grep以连字符开头的任何输出都不会被解释为第二个的选项grep

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

另请注意,反引号是将一个程序的输出获取到另一个程序的参数列表的标准方法。并非所有程序都可以像 (f)grep 那样方便地从标准输入读取参数。

于 2009-01-12T23:47:17.583 回答
5

我想在当前目录中的文件名(使用 find 找到)中具有特定模式的文件(使用 grep)中搜索文本。我使用了以下命令:

 grep -i "pattern1" $(find . -name "pattern2")

这里pattern2是文件名中的模式,而pattern1是在匹配 pattern2 的文件中搜索的模式

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

于 2012-06-21T21:10:25.117 回答
3

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

ls -la | grep 'file-in-which-to-search'
于 2013-10-08T14:35:30.753 回答
2

好的,违反规则,因为这不是答案,只是说明我无法使这些解决方案中的任何一个起作用。

% 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: line 3 in test: No such file or directory为每个找不到匹配项的文件返回一行。

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

于 2015-07-02T21:51:10.413 回答
2

我试过这种方式,效果很好。

[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]$ 
于 2017-06-01T10:19:16.510 回答
0

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

grep -l someSearch * | xargs grep otherSearch

因为在简单的 grep 上,输出的信息远不止文件名。例如,当你这样做时

grep someSearch *

您将像这样通过管道传输到 xargs 信息

filename1: blablabla someSearch blablabla something else
filename2: bla someSearch bla otherSearch
...

将上述任何一条管道传递给 xargs 都是无意义的。但是当您执行 grep -l someSearch * 时,您的输出将如下所示:

filename1
filename2

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

于 2019-05-21T13:32:40.230 回答
-1

我发现以下命令可以使用 $() 和括号内的第一个命令来让 shell 首先执行它。

grep $(dig +short) file

当我获得主机名时,我使用它来查看文件中的 IP 地址。

于 2012-06-07T13:07:47.313 回答