In awk, you'd do it as follows
awk '/pattern/{nr[NR]; nr[NR+4]}; NR in nr' file > new_file`
or
awk '/pattern/{print; nr[NR+4]; next}; NR in nr' file > new_file`
Explanation
The 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.
Example
Here's an example data file, sample.txt
.
$ cat sample.txt
1
2
3
4 blah
5
6
7
8
9
10 blah
11
12
13
14
15
16
Using the 1st solution:
$ awk '/blah/{nr[NR]; nr[NR+4]}; NR in nr' sample.txt
4 blah
8
10 blah
14
Using the 2nd solution:
$ awk '/blah/{print; nr[NR+4]; next}; NR in nr' sample.txt
4 blah
8
10 blah
14
egrep "pattern" -A4
grep -A 4 "pattern" file | sed -n '4p'
does do exactly what you want, unless I'm misunderstanding you</td>
which is not the 4th line