windowsbatch-filegnu-sed

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


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.


Solution

  • 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).