SED: addressing two lines before match

后端 未结 6 1661
梦如初夏
梦如初夏 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 06:00

    The script:

      sed -n "1N;2N;/XXX[^\n]*$/P;N;D"
    

    works as follows:

    • Read the first three lines into the pattern space, 1N;2N
    • Search for the test string XXX anywhere in the last line, and if found print the first line of the pattern space, P
    • Append the next line input to pattern space, N
    • Delete first line from pattern space and restart cycle without any new read, D, noting that 1N;2N is no longer applicable

提交回复
热议问题