我如何在每一条匹配的线周围显示前面和后面的5条线?
当前回答
grep astring myfile -A 5 -B 5
这将grep“myfile”表示“跨步”,并在每次比赛前后显示5行
其他回答
使用grep
$ grep --help | grep -i context
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
在/some/file.txt中搜索“17655”,显示前后10行上下文(使用Awk),输出前有行号,后有冒号。当grep不支持-[ACB]选项时,在Solaris上使用此选项。
awk '
/17655/ {
for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {
print before[i]
}
print (NR ":" ($0))
a = 10
}
a-- > 0 {
print (NR ":" ($0))
}
{
before[b] = (NR ":" ($0))
b = (b + 1) % 10
}' /some/file.txt;
ack使用与grep类似的参数,并接受-C。但它通常更适合于搜索代码。
我通常使用
grep searchstring file -C n # n for number of lines of context up and down
许多像grep这样的工具也有很棒的man文件。我发现自己经常参考grep的手册页,因为你可以用它做很多事情。
man grep
许多GNU工具也有一个信息页,除了手册页之外,它可能还有更多有用的信息。
info grep
-A和-B将起作用,-C n(对于n行上下文)或-n(对于n个上下文……只要n是1到9)也会起作用。