![](/img/trans.png)
[英]Unix command to fetch n lines after the grep result in bash is not working when used in conjunction with awk
[英]How do I fetch lines before/after the grep result in bash?
我想要一種在給定文本中搜索的方法。 為此,我使用grep
:
grep -i "my_regex"
這樣可行。 但鑒於這樣的數據:
This is the test data
This is the error data as follows
. . .
. . . .
. . . . . .
. . . . . . . . .
Error data ends
一旦我發現字error
(使用grep -i error data
),我希望能夠找到下面的字10行error
。 所以我的輸出應該是:
. . .
. . . .
. . . . . .
. . . . . . . . .
Error data ends
有什么辦法嗎?
您可以使用-B
和-A
在匹配前后打印行。
grep -i -B 10 'error' data
將打印匹配前的 10 行,包括匹配行本身。
這將在匹配行后打印 10 行尾隨上下文
grep -i "my_regex" -A 10
如果需要在匹配行之前打印 10 行前導上下文,
grep -i "my_regex" -B 10
如果您需要打印 10 行前導和尾隨輸出上下文。
grep -i "my_regex" -C 10
例子
user@box:~$ cat out
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$
普通的grep
user@box:~$ grep my_regex out
line 5 my_regex
user@box:~$
Grep 精確匹配行和 2 行之后
user@box:~$ grep -A 2 my_regex out
line 5 my_regex
line 6
line 7
user@box:~$
Grep 精確匹配行和 2 行之前
user@box:~$ grep -B 2 my_regex out
line 3
line 4
line 5 my_regex
user@box:~$
Grep 精確匹配行和前后 2 行
user@box:~$ grep -C 2 my_regex out
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$
參考:聯機幫助頁 grep
-A num
--after-context=num
Print num lines of trailing context after matching lines.
-B num
--before-context=num
Print num lines of leading context before matching lines.
-C num
-num
--context=num
Print num lines of leading and trailing output context.
這樣做的方法靠近手冊頁的頂部
grep -i -A 10 'error data'
試試這個:
grep -i -A 10 "my_regex"
-A 10 表示,在匹配到“my_regex”后打印十行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.