SED: addressing two lines before match

后端 未结 6 1657
梦如初夏
梦如初夏 2021-01-20 05:20

Print line, which is situated 2 lines before the match(pattern).

I tried next:

sed -n \': loop
/.*/h
:x
{n;n;/cen/p;}
s/./c/p
t x
s/n/c/p
t loop
{g;p         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 05:56

    I've tested your sed command but the result is strange (and obviously wrong), and you didn't give any explanation. You will have to save three lines in a buffer (named hold space), do a pattern search with the newest line and print the oldest one if it matches:

    sed -n '
        ## At the beginning read three lines.
        1 { N; N }
        ## Append them to "hold space". In following iterations it will append
        ## only one line.
        H 
        ## Get content of "hold space" to "pattern space" and check if the 
        ## pattern matches. If so, extract content of first line (until a 
        ## newline) and exit.
        g
        /^.*\nsix$/ { 
            s/^\n//
            P
            q 
        }
        ## Remove the old of the three lines saved and append the new one.
        s/^\n[^\n]*//
        h
    ' infile
    

    Assuming and input file (infile) with following content:

    one
    two
    three
    four
    five
    six
    seven
    eight
    nine
    ten
    

    It will search six and as output will yield:

    four
    

提交回复
热议问题