Search for text between two patterns with multiple lines in between

后端 未结 3 1964
[愿得一人]
[愿得一人] 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
    

提交回复
热议问题