3

最近我需要在文件中搜索特定的字符串,我需要显示匹配之前的行和匹配之后的行。

文件

AAAA
BBBB                      
中国交建
DDDD

使用谷歌,我找到了以下使用 grep 的解决方案。

grep -n1 BBBB File

哪个输出,

1-AAAA
2-BBBB
3-CCCC

所以这就是我想要的,除了它在输出中显示行号。

有没有办法抑制行号?

4

2 回答 2

5

用这个:

grep -C 1 BBBB input

grep具有显示上下文行的三个选项:

  -A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  Places a line  containing  --  between  contiguous  groups  of
          matches.
  -B NUM, --before-context=NUM
          Print  NUM  lines  of  leading  context  before matching lines.  Places a line containing -- between contiguous groups of
          matches.
  -C NUM, --context=NUM
          Print NUM lines of output context.  Places a line containing -- between contiguous groups of matches.
于 2013-06-13T01:27:45.707 回答
2

只需删除n

grep -1 BBBB input

也与sed

sed -n 'N;N;/\n.*BBBB.*\n/p' input
于 2013-06-13T00:50:30.237 回答