【问题标题】:grep to find a string, get the line before and after with no line numbers displayedgrep 查找字符串,获取前后行,不显示行号
【发布时间】:2013-06-13 00:44:51
【问题描述】:

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

文件

AAAA BBBB 中国交建 DDDD

使用 google 我找到了以下使用 grep 的解决方案。

grep -n1 BBBB File

哪些输出,

1-AAAA
2-BBBB
3-CCCC

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

有没有办法抑制行号?

【问题讨论】:

    标签: grep


    【解决方案1】:

    使用这个:

    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.
    

    【讨论】:

    • 太酷了!这样我就可以在之前、之后或两者中获得 X 行!那会派上用场的,谢谢!
    【解决方案2】:

    只需删除n

    grep -1 BBBB input
    

    还有sed

    sed -n 'N;N;/\n.*BBBB.*\n/p' input
    

    【讨论】:

    • 效果很好!谢谢,你可能发现我是新手 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2012-10-18
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 2014-03-28
    相关资源
    最近更新 更多