9

特定のパターン (棒線など) を検索したいだけでなく、パターンの上下 (つまり 1 行) またはパターンの上下 2 行を印刷したいと考えています。

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....
4

2 に答える 2

18

grepパラメータ-Aと一緒に使用して、パターンの周りに印刷する前後-Bの行数を示しAます。B

grep -A1 -B1 yourpattern file
  • Ann試合の「後」の行を表します。
  • Bmm試合の「前」のラインを表します。

両方の数値が同じ場合は、次を使用します-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.
于 2013-10-11T08:21:06.867 に答える
3

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
于 2013-10-11T08:28:47.500 に答える