Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

sed: remove between delimeters IF a string is present between them

Right now I have a multiline string matching this format:

---
some text
more text
MATCH: FIRST
more text
---
some text
more text
---
some text
MATCH: SECOND
more text
---
some
more
MATCH: THIRD
text
here
---

I'm looking for a way in bash (preferably using sed) to remove everything between --- and --- if MATCH: FIRST or MATCH: SECOND are present between them. i.e. for the above example I would want my output to look like:

---
some text
more text
---
some
more
MATCH: THIRD
text
here
---

For my purposes I don't really care either way if the delimiters are removed (the ---). Any help is appreciated.

The closest I've gotten is doing something along these lines:

sed -e "/---*[MATCH: ]FIRST|SECOND[^---]/,/---/d"

but I seem to be missing something.

question from:https://stackoverflow.com/questions/65890105/sed-remove-between-delimeters-if-a-string-is-present-between-them

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The --- are easily repeatable and easily to "catch". Accumulate blocks separated by --- into hold space, then match the whole hold space with the searched pattern. If it does not match, print it.

The following shell script:

cat <<EOF |
---
some text
more text
MATCH: FIRST
more text
---
some text
more text
---
some text
MATCH: SECOND
more text
---
some
more
MATCH: THIRD
text
here
---
moretest
---
andnaotherone
---
MATCH: SECOND
---
MATCH: SECOND
---
EOF
sed -n '
/^---$/!{H;b} # Accumulate one block
H;x;
# If there is the searched pattern
/
MATCH: (FIRST|SECOND)
/!{
    s/^
// # the leading newline from H
    p
} ; : OKEY
# Clear hold space so its empty
s/.*//;h
b
'

outputs:

---                                                                                                                                     
some text
more text
---
some
more
MATCH: THIRD
text
here
---
moretest
---
andnaotherone
---

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...