简体   繁体   中英

sed: remove strings between two patterns leaving the 2nd pattern intact (half inclusive)

I am trying to filter out text between two patterns, I've seen a dozen examples but didn't manage to get exactly what I want:

Sample input:

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 an inclusive removal, I tried adding "exclusions" (not sure if I really understand this syntax well):

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

But my "START DELETEME" line is still there (yes, I can grep it out, but that's ugly :) and besides - it DOES remove the empty line in this sample as well and I'd like to leave empty lines if they are my end pattern intact ) I am wondering if there is a way to do it 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 runs like a snail". It takes forever.

Thanks in advance. Dave.

在sed中使用循环:

sed -n '/^START DELETEME/{:l n; /^[ ]/bl};p' input

GNU sed

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

I would stick with awk:

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

But if you still prefer sed, here's another way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM