gpt4 book ai didi

grep - 如何grep在特定模式上方和下方的线条

转载 作者:行者123 更新时间:2023-12-04 22:05:20 25 4
gpt4 key购买 nike

我想搜索某个图案(比如条形线),但还要在图案上方和下方(即 1 行)或图案上方和下方打印 2 行。

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....

最佳答案

使用 grep带参数-A-B表示行数 a 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 - 如何grep在特定模式上方和下方的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19313494/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com