如何使用grep
命令并显示每个匹配行前后的5行内容?
如何使用grep
命令并显示每个匹配行前后的5行内容?
如果您使用的是BSD或GNU grep
,则可以使用-B num
来设置匹配前几行的数量,-A num
用于设置匹配后几行的数量。
grep -B 3 -A 2 foo README.txt
如果您希望在输出结果中保留相同数量的行数,您可以使用 -C num
命令。
grep -C 3 foo README.txt
这将显示前3行和后3行。
-A
和 -B
都可以使用,-C n
(用于显示上下文的 n
行),或者只需使用 -n
(用于显示上下文的 n
行,只要 n
是1到9之间的数字)。
ack使用与grep相似的参数,并接受-C
,但通常更适用于搜索代码。
grep
的,不确定用它来“宣传” ack
(确实是一个很棒的工具)是否是一个好主意... - MonsieurDartgrep astring myfile -A 5 -B 5
ripgrep
如果你关心性能,建议使用 ripgrep
,它具有类似于grep
的语法,例如:
rg -C5 "pattern" .
-C
,--context NUM
- 显示每个匹配之前和之后的NUM行。
还有一些参数,如-A
/--after-context
和-B
/--before-context
。
该工具构建在Rust的正则表达式引擎上,使其在处理大数据时非常高效。
我通常使用
grep searchstring file -C n # n for number of lines of context up and down
许多工具,如grep,也有非常棒的man文件。我经常参考grep的man页面,因为你可以用它做很多事情。
man grep
许多GNU工具还有一个信息页面,除了手册页可能还包含更多有用的信息。
info grep
让我们通过一个例子来理解。
我们可以使用带有选项的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
记忆选项的技巧:
-A
→ A 意味着 "After(之后)"-B
→ B 意味着 "Before(之前)"-C
→ C 意味着 "在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
如果你经常搜索代码,AG 比 grep 更高效(即更快)。
使用 -C
选项可以显示上下文行。
例如:
ag -C 3 "foo" myFile
line 1
line 2
line 3
line that has "foo"
line 5
line 6
line 7
在Solaris上,当grep
不支持-[ACB]
选项时,在/some/file.txt
中搜索“17655”,显示前后10行内容(使用Awk
),输出以行号加冒号为前缀。
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;
man grep | grep -C 1 context
来查找与 "context" 相关的文本内容,其中grep
命令可用于在文本中搜索匹配的字符串,而man
命令用于显示 Linux 系统中的手册页面。 - StvnW