1

Input file is like this:

AAAAAAAAAAA
BBBBBBBBBBB
Start
CCCCCCCCCCC
DDDDDDDDDDD
Stop
EEEEEEEEEEE
Stop
Rec
FFFFFFFFFFF
GGGGGGGGGGG
HHHHHHHHHHH
Start
IIIIIIIIIII
JJJJJJJJJJJ
Start
KKKKKKKKKKK
LLLLLLLLLLL
MMMMMMMMMMM
NNNNNNNNNNN
Stop
Rec
OOOOOOOOOOO
PPPPPPPPPPP
QQQQQQQQQQQ
RRRRRRRRRRR
SSSSSSSSSSS
TTTTTTTTTTT
UUUUUUUUUUU
VVVVVVVVVVV
Start
WWWWWWWWWWW
XXXXXXXXXXX
YYYYYYYYYYY
ZZZZZZZZZZZ

Desired output:

AAAAAAAAAAA
BBBBBBBBBBB
FFFFFFFFFFF
GGGGGGGGGGG
HHHHHHHHHHH
Start
IIIIIIIIIII
JJJJJJJJJJJ
OOOOOOOOOOO
PPPPPPPPPPP
QQQQQQQQQQQ
RRRRRRRRRRR
SSSSSSSSSSS
TTTTTTTTTTT
UUUUUUUUUUU
VVVVVVVVVVV
Start
WWWWWWWWWWW
XXXXXXXXXXX
YYYYYYYYYYY
ZZZZZZZZZZZ

I want to remove all the lines between tags Start and tags Stop\nRec (tags included). The Start-Stop\nRec sequence can appear many times in a long file. AAAAAA, BBBBBB, ...ZZZZZZ lines can be anything. The tags (Start and Stop\nRec) do not share their line with data (i.e. must be searched as ^tag$. The end tag Stop\nRec has to be 2-lines tag.

But, when several Start are found before a Stop\nRec is found, the suppression must only apply from the last Start found before the Stop\nRec (in example, lines IIIIIII and JJJJJJJ are kept).

And, at the end of the file, when a Start tag is encountered but no Stop\nRec tag, the lines between this Start and the end of file must be kept (in example, lines Start WWWWWW XXXXXX YYYYYY ZZZZZZ are kept).

I want to do this rework with sed (running under bash shell on Linux) and using the -i option (same file for input and output).

I did the following, but it doesn't work properly (especialy when several Start tag are encoutered before a Stop\nRec tag is reached):

sed -i '/^Start\n/ {:a; $!{ N ; /\nStop\nRec$/!ba } s/.*// }' file.txt

Thanks in advance for your help.

  • 1
    Can there be cases where Rec is not preceded by Stop or can we assume that Rec is a stop tag always? – terdon Jul 6 '16 at 14:10
0

This seems to work:

${H;x;p;q}
/Start/ {x;s/^\n//;p;d}
{H;N}
/Stop\nRec/ {s/.*//;h;d}
D
0

Try to test

sed '
    /Start/! b
    :a
    /\nStart$/{
        P
        D
    }
    N
    $b
    /Stop\nRec/! ba
    d
' Input.file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.