0

现在我有一个匹配这种格式的多行字符串:

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

我正在寻找一种在 bash 中的方法(最好使用 sed)来删除它们之间---以及它们之间---是否存在的所有内容。即对于上面的例子,我希望我的输出看起来像:MATCH: FIRSTMATCH: SECOND

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

出于我的目的,我并不关心分隔符是否被删除(the ---)。任何帮助表示赞赏。

我得到的最接近的是沿着这些方向做一些事情:

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

但我似乎错过了一些东西。

4

1 回答 1

0

---它们很容易重复并且很容易“抓住” 。将分隔的块累积---到保持空间中,然后将整个保持空间与搜索的模式匹配。如果不匹配,请打印。

以下外壳脚本:

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
/\nMATCH: \(FIRST\|SECOND\)\n/!{
    s/^\n// # the leading newline from H
    p
} ; : OKEY
# Clear hold space so its empty
s/.*//;h
b
'

输出:

---                                                                                                                                     
some text
more text
---
some
more
MATCH: THIRD
text
here
---
moretest
---
andnaotherone
---
于 2021-01-29T22:47:01.747 回答