特定のパターン (棒線など) を検索したいだけでなく、パターンの上下 (つまり 1 行) またはパターンの上下 2 行を印刷したいと考えています。
Foo line
Bar line
Baz line
....
Foo1 line
Bar line
Baz1 line
....
特定のパターン (棒線など) を検索したいだけでなく、パターンの上下 (つまり 1 行) またはパターンの上下 2 行を印刷したいと考えています。
Foo line
Bar line
Baz line
....
Foo1 line
Bar line
Baz1 line
....
grep
パラメータ-A
と一緒に使用して、パターンの周りに印刷する前後-B
の行数を示しA
ます。B
grep -A1 -B1 yourpattern file
An
n
試合の「後」の行を表します。Bm
m
試合の「前」のラインを表します。両方の数値が同じ場合は、次を使用します-C
。
grep -C1 yourpattern file
$ cat file
Foo line
Bar line
Baz line
hello
bye
hello
Foo1 line
Bar line
Baz1 line
しましょうgrep
:
$ grep -A1 -B1 Bar file
Foo line
Bar line
Baz line
--
Foo1 line
Bar line
Baz1 line
グループセパレーターを取り除くには、次を使用できます--no-group-separator
。
$ grep --no-group-separator -A1 -B1 Bar file
Foo line
Bar line
Baz line
Foo1 line
Bar line
Baz1 line
から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
はあなたのためのツールですが、それはで行うことができますawk
awk '{a[NR]=$0} $0~s {f=NR} END {for (i=f-B;i<=f+A;i++) print a[i]}' B=1 A=2 s="Bar" file
NB これも 1 つのヒットを検出します。
またはgrep
grep -A2 -B1 "Bar" file