我如何在每一条匹配的线周围显示前面和后面的5条线?


当前回答

Grep有一个名为Context Line Control的选项,您可以使用--Context,

| grep -C 5

or

| grep -5

应该会成功的

其他回答

ack使用与grep类似的参数,并接受-C。但它通常更适合于搜索代码。

在/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;

让我们用一个例子来理解。我们可以使用带有选项的grep:

-A 5  # this will give you 5 lines after searched string.
-B 5  # this will give you 5 lines before searched string.
-C 5  # this will give you 5 lines before & after searched string

实例File.txt包含6行,以下是操作。

[abc@xyz]~/% cat file.txt # print all file data
this is first line
this is 2nd line
this is 3rd line
this is 4th line
this is 5th line
this is 6th line

[abc@xyz]~% grep "3rd" file.txt # we are searching for keyword '3rd' in the file
this is 3rd line

[abc@xyz]~% grep -A 2 "3rd" file.txt # print 2 lines after finding the searched string
this is 3rd line
this is 4th line
this is 5th line

[abc@xyz]~% grep -B 2 "3rd" file.txt # Print 2 lines before the search string.
this is first line
this is 2nd line
this is 3rd line

[abc@xyz]~% grep -C 2 "3rd" file.txt # print 2 line before and 2 line after the searched string 
this is first line
this is 2nd line
this is 3rd line
this is 4th line
this is 5th line

记住选项的技巧:选项:

-一个 -> 之后的平均值-B级 -> B表示之前。-c类 -> 介于两者之间

使用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

里普雷普

如果您关心性能,请使用与grep语法相似的ripgrep,例如。

rg -C5 "pattern" .

-C、 --context NUM—在每次匹配前后显示NUM行。

还有一些参数,如-A/-after上下文和-B/-before上下文。

该工具构建在Rust的正则表达式引擎之上,这使得它对大数据非常有效。