Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sed match pattern and print two lines before pattern and all lines upto end of file

sample

tyu
abc

def
ghi
fgg
yui

Output

abc

def
ghi
fgg
yui

Matching pattern : ^def
Print two lines before matching line including pattern and print all lines after pattern until end

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

1st solution: With your shown samples try following awk code, written and tested in GNU awk.

awk -v RS='(^|\n)def.*' '
RT{
  num=split($0,arr,ORS)
  sub(/\n$/,"",RT)
  print arr[num-1] ORS arr[num]  RT
}
' Input_file


2nd solution(More Generic one): In this solution one could mention number of lines needed to be printed before a match is found in awk‘s variable named lines and we need NOT to hardcode number of times we need to print array’s element(in split function for first line).

awk -v lines="2" -v RS='(^|\n)def.*' '
RT{
  val=""
  num=split($0,arr,ORS)
  sub(/\n$/,"",RT)
  for(i=lines;i<=num;i++){
    val=(val?val ORS:"") arr[i]
  }
  print val RT
}
'  Input_file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading