sed if pattern match copy pattern line along with n number of lines after this to another file

82 Views Asked by At

I am looking for a sed command to match pattern and copy pattern line and n number of lines after this line. pattern is 01, 02, 03 sequence.

Example:

group-title=01- line1
http://www.yahoo.com
group-title=02- local3
http://www.altavista.com
group-title=01- koko1
http://www.bbc.com

Required output:

group-title=01- line1
http://www.yahoo.com
group-title=01- koko1
http://www.bbc.com

I tried

sed -n "/01- /p" orignal.txt > copyof.txt

but this only copy line which matches pattern. I have to copy the 2nd line also as second line has its link.

3

There are 3 best solutions below

9
Gordon Davisson On BEST ANSWER

grep -A is the better way to do this (see Timur Shtatland's answer), but if you really want to do it with sed, here's how:

sed -n '/01- / {p;n;p;}'      # print match + next line
sed -n '/01- / {p;n;p;n;p;}'  # print match + next 2 lines

Explanation: when it finds a matching line, {p;n;p;} will print that line, get the next line, and print that.

Note that this won't notice additional matches within the extra lines being printed. So for example if there are two matching lines in a row, it'll print them but not the next line as you might expect (and grep -A will do).

1
Timur Shtatland On

Use grep:

grep -A1 'group-title=01-' orig.txt > copy.txt

Here, GNU grep uses option:

-A num, --after-context=num : Print num lines of trailing context after each match. See also the -B and -C options.

1
sseLtaH On

Using GNU sed

$ sed -Ez ':a;s/(([^=]*=)01-[^=]*)\20[02-9][^=]*\n/\1/;ta' input_file
group-title=01- line1
http://www.yahoo.com
group-title=01- koko1
http://www.bbc.com