Extract Nth line after matching pattern

后端 未结 3 1409
借酒劲吻你
借酒劲吻你 2020-12-15 01:26

I want to extract the Nth line after a matching pattern using grep, awk or sed.

For example I have this piece of text:

3条回答
  •  执念已碎
    2020-12-15 02:03

    To extract the Nth line after a matching pattern you want:

    awk 'c&&!--c;/pattern/{c=N}' file
    

    e.g.

    awk 'c&&!--c;/Revision:/{c=5}' file
    

    would print the 5th line after the text "Revision:"/.

    FYI the following idioms describe how to select a range of records given a specific pattern to match:

    a) Print all records from some pattern:

    awk '/pattern/{f=1}f' file
    

    b) Print all records after some pattern:

    awk 'f;/pattern/{f=1}' file
    

    c) Print the Nth record after some pattern:

    awk 'c&&!--c;/pattern/{c=N}' file
    

    d) Print every record except the Nth record after some pattern:

    awk 'c&&!--c{next}/pattern/{c=N}1' file
    

    e) Print the N records after some pattern:

    awk 'c&&c--;/pattern/{c=N}' file
    

    f) Print every record except the N records after some pattern:

    awk 'c&&c--{next}/pattern/{c=N}1' file
    

    g) Print the N records from some pattern:

    awk '/pattern/{c=N}c&&c--' file
    

    I changed the variable name from "f" for "found" to "c" for "count" where appropriate as that's more expressive of what the variable actually IS.

提交回复
热议问题