n < code $> code> m $ c>
$ b $如果两个数字相同,只需使用 -C
: grep -C1 yourpattern file
T est
$ cat file
Foo line
Bar line
Baz line
你好
再见
你好
Foo1线
杠线
Baz1线
让我们 grep
:
$ grep -A1 -B1条形文件
Foo线
条线
Baz线
-
Foo1线
线条线
Baz1线
要摆脱组分隔符,可以使用 - no-group-分隔符
:
$ grep --no-group-separator -A1 -B1条形文件
Foo line
Bar line
Baz line
Foo1 line
Bar line
Baz1 line
从 man grep
:
-A NUM,--after-context = NUM
打印匹配行后的尾行上下文的NUM行。
在
连续的匹配组之间放置一个包含组分隔符( - )的行。使用-o或--only-matching
选项,这不起作用并给出警告。
-B NUM,--before-context = NUM
在匹配行之前打印前导上下文的NUM行。
在
连续的匹配组之间放置一个包含组分隔符( - )的行。使用-o或--only-matching
选项,这不起作用并给出警告。
-C NUM,-NUM,--context = NUM
打印输出上下文的NUM行。在连续的匹配组之间放置一个包含
组分隔符( - )的行。使用
的-o或--only-matching选项,这不起作用,并给出
的警告。
I would like to search for a certain pattern (say Bar line) but also print lines above and below (i.e 1 line) the pattern or 2 lines above and below the pattern.
Foo line
Bar line
Baz line
....
Foo1 line
Bar line
Baz1 line
....
解决方案
Use grep
with the parameters -A
and -B
to indicate the number a of lines A
fter and B
efore you want to print around your pattern:
grep -A1 -B1 yourpattern file
An
stands for n
lines "after" the match.
Bm
stands for m
lines "before" the match.
If both numbers are the same, just use -C
:
grep -C1 yourpattern file
Test
$ cat file
Foo line
Bar line
Baz line
hello
bye
hello
Foo1 line
Bar line
Baz1 line
Let's grep
:
$ grep -A1 -B1 Bar file
Foo line
Bar line
Baz line
--
Foo1 line
Bar line
Baz1 line
To get rid of the group separator, you can use --no-group-separator
:
$ grep --no-group-separator -A1 -B1 Bar file
Foo line
Bar line
Baz line
Foo1 line
Bar line
Baz1 line
From man grep
:
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a
group separator (--) between contiguous groups of matches. With
the -o or --only-matching option, this has no effect and a
warning is given.
这篇关于如何在特定模式之上和之下的线条进行grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!