Search for text between two patterns with multiple lines in between

后端 未结 3 1919
[愿得一人]
[愿得一人] 2021-01-28 15:15

I have a simple question. I have a file containing:

more random text

*foo*
there
is 
random
text
here
*foo*

foo
even
more
random
text
here
foo
more random text         


        
相关标签:
3条回答
  • 2021-01-28 15:46

    With sed:

    $ sed -n '/foo/{:a;n;/foo/q;p;ba}' infile
    there
    is
    random
    text
    here
    

    Explained:

    /foo/ {     # If we match "foo"
        :a      # Label to branch to
        n       # Discard current line, read next line (does not print because of -n)
        /foo/q  # If we match the closing "foo", then quit
        p       # Print line (is a line between two "foo"s)
        ba      # Branch to :a
    }
    

    Some seds complain about braces in one-liners; in those cases, this should work:

    sed -n '/foo/ {
        :a
        n
        /foo/q
        p
        ba
    }' infile
    
    0 讨论(0)
  • 2021-01-28 15:56

    Since checking for "foo" (using /foo/) is relatively expensive, the following avoids that check and will work with all awks worthy of the name:

    awk 'c==2 {next} /foo/{++c;next} c==1' file
    
    0 讨论(0)
  • 2021-01-28 16:01
    $ awk '/foo/{++c;next} c==1' file
    there
    is
    random
    text
    here
    
    $ awk '/foo/{++c;next} c==3' file
    even
    more
    random
    text
    here
    

    or with GNU awk for multi-char RS you COULD do:

    $ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==2' file
    there
    is
    random
    text
    here
    
    $ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==4' file
    even
    more
    random
    text
    here
    

    See https://stackoverflow.com/a/17914105/1745001 for other ways of printing after a condition is true.

    0 讨论(0)
提交回复
热议问题