SED: addressing two lines before match

后端 未结 6 1658
梦如初夏
梦如初夏 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:04

    Here are some other variants:

    awk '{a[NR]=$0} /pattern/ {f=NR} END {print a[f-2]}' file
    

    This stores all lines in an array a. When pattern is found store line number.
    At then end print that line number from the file.
    PS may be slow with large files


    Here is another one:

    awk 'FNR==NR && /pattern/ {f=NR;next} f-2==FNR' file{,}
    

    This reads the file twice (file{,} is the same as file file)
    At first round it finds the pattern and store line number in variable f
    Then at second round it prints the line two before the value in f

提交回复
热议问题