用 sed 删除大括号对之间的所有内容 [英] Remove everything between pairs of braces with sed
问题描述
我有一个看起来像这样的字符串:
I've got a string that looks like this:
[%{%B%F{blue}%}master %{%F{red}%}*%{%f%k%b%}%{%f%k%b%K{black}%B%F{green}%}]
我想删除与 %{...}
匹配的子字符串,这些子字符串可能包含也可能不包含相同顺序的其他子字符串.
I want to remove the substrings matching %{...}
, which may or may not contain further substrings of the same order.
我应该得到:[master *]
作为最终输出.我目前的进展:
I should get: [master *]
as the final output. My progress so far:
gsed -E 's/%\{[^\}]*\}//g'
给出:
echo '[%{%B%F{blue}%}master %{%F{red}%}*%{%f%k%b%}%{%f%k%b%K{black}%B%F{green}%}]' | gsed -E 's/%\{[^\}]*\}//g'
[%}master %}*%B%F{green}%}]
因此,这适用于 %{...}
部分,这些部分不包含 %{...}
.对于像 %{%B%F{blue}%}
这样的字符串,它会失败(它返回 %}
).
So, this works fine for %{...}
sections which do not contain %{...}
. It fails for strings like %{%B%F{blue}%}
(it returns %}
).
我想要做的是解析字符串,直到找到匹配 }
,然后删除到该点的所有内容,而不是删除 % 之间的所有内容{
和我遇到的第一个 }
.我不知道该怎么做.
What I want to do is parse the string until I find the matching }
, then remove everything up to that point, rather than removing everything between %{
and the first }
I encounter. I'm not sure how to do this.
我完全意识到可能有多种方法可以做到这一点;如果可能的话,我更喜欢关于问题中指定方式的答案,但任何想法都非常受欢迎.
I'm fully aware that there are probably multiple ways to do this; I'd prefer an answer regarding the way specified in the question if it is possible, but any ideas are more than welcome.
推荐答案
这可能对你有用:
echo '[%{%B%F{blue}%}master %{%F{red}%}*%{%f%k%b%}%{%f%k%b%K{black}%B%F{green}%}]' |
sed 's/%{/{/g;:a;s/{[^{}]*}//g;ta'
[master *]
这篇关于用 sed 删除大括号对之间的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!