Sed: delete lines between two patterns, leaving the 2nd pattern intact (half inclusive)

I am trying to filter text between two templates, I have seen a dozen examples, but I have not been able to get exactly what I want:

Input Example:

START LEAVEMEBE text data START DELETEME text data more data even more START LEAVEMEBE text data more data START DELETEME text data more SOMETHING that doesn't start with START @ sometimes it starts with characters that needs to be escaped... 

I want to stay with:

 START LEAVEMEBE text data START LEAVEMEBE text data more data SOMETHING that doesn't start with START @ sometimes it starts with characters that needs to be escaped... 

I tried running sed with:

 sed 's/^START DELETEME/,/^[^ ]/d' 

And got the deletion included, I tried adding “exceptions” (not sure if I really understand this syntax well):

 sed 's/^START DELETEME/,/^[^ ]/{/^[^ ]/!d}' 

But my line “START DELETEME” still exists (yes, I can do it, but it's ugly :) and besides - it also deletes the empty line in this example, and I would like to leave empty lines if this is mine end, untouched) I wonder if there is a way to do this with a single sed command. I have an awk script that does this well:

 BEGIN { flag = 0 } { if ($0 ~ "^START DELETEME") flag=1 else if ($0 !~ "^ ") flag=0 if (flag != 1) print $0 } 

But, as you know, "A is for awk, which works like a snail." It is required forever.

Thanks in advance. Dave

+4
source share
3 answers

Using a loop in sed:

 sed -n '/^START DELETEME/{:ln; /^[ ]/bl};p' input 
+1
source

GNU sed

 sed '/LEAVEMEBE/,/DELETEME/!d;{/DELETEME/d}' file 
+1
source

I would stick with awk:

 awk ' /LEAVE|SOMETHING/{flag=1} /DELETE/{flag=0} flag' file 

But if you still prefer sed, here is another way:

 sed -n ' /LEAVE/,/DELETE/{ /DELETE/b p } ' file 
0
source

Source: https://habr.com/ru/post/1485935/


All Articles