如何让grep首先输出文件名,然后输出多行上下文

时间:2013-03-18 02:48:15

标签: bash grep

我希望grep的输出类似于:

path/filename1-
line1
match
line3
--
path/filename2-
line1
match
line3

如果我做grep -h -C 3 match file我接近,但没有文件名。从手册页我看不到任何其他选项。

2 个答案:

答案 0 :(得分:1)

ack正是如此。

$ ack get -C3
unuse
7-
8-my $url = shift || die 'specify a URL';
9-
10:$mech->get( $url );
11-
12-my $text = $mech->content;
13-

whack
47-    Note that this script uses PPI and works only on perl
48-    scripts, modules, tests, etc. PPI takes a bit of time
49-    too, so if running this on an entire large repo, you
50:    may want to multitask or get some coffee.
51-
52-    By default, searches recursively for perl files in . and
53-    identifies the subroutine most likely to invoke confusion

另请注意,虽然此处未显示,但输出采用颜色编码。文件名(本例中为“unuse”和“whack”)为绿色,行号为黄色,匹配的字符串为黄色。

ack是一个像grep这样专门面向程序员的搜索工具。它可以在http://betterthangrep.com获得,许多* nix发行版都将它作为一个包。 Debian派生的软件包将ack命名为“ack-grep”。

答案 1 :(得分:0)

我认为你不能用grep直接做到这一点。你也许可以写一个包装器,也许用sed就可以了。如果使用-Z标志,那么grep会将文件名与匹配的部分分开(因此也使用-H来获取文件名)。然后可能跟踪当前文件名,当它改变时将其打印出来,然后换行,但是否则只是从匹配行的前面删除它。想想看,perl也会起作用