I am trying to print the matched line and the 4th line from the matched line (line containing the expression I am searching for).I have been using the following code:sed -n 's/^[ \t]*//; /img class=\devil_icon/,4p' input.txtBut this only prints the matched line.This prints only the 4th line.awk 'c&&!--c;/img class=\devil_icon/{c=4}' input.txtI need to print both the matched line and the 4th line only.
Print Matching line and nth line from the matched line
shell script
In awk, you'd do it as followsawk '/pattern/{nr[NR]; nr[NR+4]}; NR in nr' file > new_file`orawk '/pattern/{print; nr[NR+4]; next}; NR in nr' file > new_file`ExplanationThe first solution finds all lines that match pattern. When it finds a match it stores the record number (NR) in the array nr. It also stores the 4th record from NR in the same array. This is done by the nr[NR+4]. Every record (NR) is then checked to see if it's present in the nr array, if so the record is printed. The second solution works essentially the same way, except when it encounters th e pattern it prints that line, and then stores the 4th record ahead of it in the array nr, then goes to the next record. Then when awk encounters this 4th record the NR in nr block will get executed and print this +4 record there after.ExampleHere's an example data file, sample.txt.$ cat sample.txt 1234 blah5678910 blah111213141516Using the 1st solution:$ awk '/blah/{nr[NR]; nr[NR+4]}; NR in nr' sample.txt 4 blah810 blah14Using the 2nd solution:$ awk '/blah/{print; nr[NR+4]; next}; NR in nr' sample.txt 4 blah810 blah14