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

>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

Leave a Reply