如何替换字符串中的字符,但仅当它出现在带分隔符的子字符串中时才如何? [英] How to replace a character in a string but only if it occurs within a delimited substring?
问题描述
我想用一个字符串中的另一个字符替换一个字符,但是仅当该字符出现在该字符串的带分隔符的子字符串中时才可以.例如,对于字符串:
I would like to replace a character with another character in a string but only when the character occurs within a delimited substring of the string. For example, for the string:
b [b] abc [abc] bbb [bbb]
b[b]abc[abc]bbb[bbb]
仅在方括号"[...]"之内,我想将"b"更改为"x".因此,所需的结果是字符串:
I would like to change "b" to "x" but only if it is within square brackets "[...]". Thus, the desired result is the string:
b [x] abc [axc] bbb [xxx]
b[x]abc[axc]bbb[xxx]
我更喜欢sed或bash解决方案,因为它们在我的舒适范围内,但是任何适用于Mac OS X的解决方案都可以.通过搜索,似乎可以使用sed使用负向超前和负向后向实现,但是我不认为这些功能在Mac版本的sed上可用.
My preference would be a sed or bash solution because they are in my comfort zone, but any solution that would work for Mac OS X would be fine. From searching, it seems that this can be accomplished with sed using negative lookahead and negative lookbehind, but I don't believe those features are available on the Mac version of sed.
推荐答案
使用GNU sed:
$ sed -r ':a;s/(\[[^]]*)b/\1x/;ta' <<< "b[b]abc[abc]bbb[bbb]"
b[x]abc[axc]bbb[xxx]
-
:a
为即将到来的循环添加标签 -
s
:替代命令 -
(\[[^]]*)
:搜索并捕获[
,后跟任何非]
字符 - 直到找到
b
- 匹配字符串将替换为最初捕获的字符串和
x
-
ta
:如果先前的替换成功,则循环标记为:a
(替换任何其他出现的b
) :a
adds a label for upcoming loops
: substitute command(\[[^]]*)
: search and capture a[
followed by any non-]
character- until
b
is found - matching string is replaced with initially captured string and a
x
ta
: if previous substitution succeed, loops to label:a
(replace any other occurrence ofb
)
对于OS X上的GNU sed:
For GNU sed on OS X :
brew uninstall gnu-sed
这篇关于如何替换字符串中的字符,但仅当它出现在带分隔符的子字符串中时才如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!