Pawel Bala
Pawel Bala

Reputation: 93

tricky multiline erase in SED

here is the input:

aaa
bbb
ccc
ddd
eee
fff

what I want? do sth like" sed "/ccc/,/(eee)/d" BUT ALSO DELETE "bbb" line (before "ccc") so that output is:

aaa
fff

any ideas?

Upvotes: 0

Views: 90

Answers (3)

potong
potong

Reputation: 58381

This might work for you (GNU sed):

sed ':a;$!{N;/\nccc/!{P;D};/\neee/!ba;d}' file

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203349

You could do this in a simple 2-pass approach, first pass to identify the lines to delete and the second pass to print only the lines that are not marked for deletion:

awk '/ccc/,/eee/{d[NR]=d[NR-1]=1} NR!=FNR && !d[FNR]' file file

Upvotes: 0

Guru
Guru

Reputation: 16974

If you are fine with awk, this should do:

$ awk '/ccc/,/eee/{if(i!=1){i=1;x="";}next}{if (x)print x;x=$0;}END{print x}' file
aaa
fff

Every previous line is printed in the above case. Normal range filtering is done using awk. However, within the range filter, the variable x is reset so that the previous record just before the range is not printed.

Update:

sed solution:

$ sed '${x;p;};/ccc/,/eee/{/ccc/{s/.*//;x;};d;};1{h;d;};x;/^$/d;' file

Upvotes: 0

Related Questions