[英]Sed substitute recursively
echo ddayaynightday | sed 's/day//g'
It ends up daynight
它结束了
daynight
Is there anyway to make it substitute until no more match ? 无论如何都要让它替代直到不再匹配?
My preferred form, for this case: 我喜欢的形式,对于这种情况:
echo ddayaynightday | sed -e ':loop' -e 's/day//g' -e 't loop'
This is the same as everyone else's, except that it uses multiple -e commands to make the three lines and uses the t
construct—which means "branch if you did a successful substitution"—to iterate. 这和其他人一样,除了它使用多个-e命令来制作三行并使用
t
构造 - 这意味着“如果你做了一个成功的替换就分支” - 迭代。
This might work for you: 这可能对你有用:
echo ddayaynightday | sed ':a;s/day//g;ta'
night
The g
flag deliberately doesn't re-match against the substituted portion of the string. g
标志故意不与字符串的替换部分重新匹配。 What you'll need to do is a bit different. 你需要做的是有点不同。 Try this:
试试这个:
echo ddayaynightday | sed $':begin\n/day/{ s///; bbegin\n}'
Due to BSD Sed's quirkiness the embedded newlines are required. 由于BSD Sed的怪癖,需要嵌入的换行符。 If you're using GNU Sed you may be able to get away with
如果你正在使用GNU Sed,你可能会逃脱
sed ':begin;/day/{ s///; bbegin }'
The following works: 以下作品:
$ echo ddayaynightday | sed ':loop;/day/{s///g;b loop}'
night
Depending on your system, the ;
根据您的系统,
;
may not work to separate commands, so you can use the following instead: 可能无法分离命令,因此您可以使用以下代码:
echo ddayaynightday | sed -e ':loop' -e '/day/{s///g
b loop}'
Explanation: 说明:
:loop # Create the label 'loop'
/day/{ # if the pattern space matches 'day'
s///g # remove all occurrence of 'day' from the pattern space
b loop # go back to the label 'loop'
}
If the b loop
portion of the command is not executed, the current contents of the pattern space are printed and the next line is read. 如果未执行命令的
b loop
部分,则打印模式空间的当前内容并读取下一行。
with bash: 用bash:
str=ddayaynightday
while true; do tmp=${str//day/}; [[ $tmp = $str ]] && break; str=$tmp; done
echo $str
Ok, here they're: while and strlen in bash. 好吧,在这里他们是: 而在 strash中strlen 。 Using them one may implement my idea:
使用它们可以实现我的想法:
Repeat until its length will stop changing.
重复直到其长度停止变化。
There's neither way to set flag nor way to write such regex, to "substitute until no more match". 既没有办法设置标志也没有办法写这样的正则表达式,以“替换直到不再匹配”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.