Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 多重匹配模式中的字符替换_Regex_Bash_Shell_Awk_Sed - Fatal编程技术网

Regex 多重匹配模式中的字符替换

Regex 多重匹配模式中的字符替换,regex,bash,shell,awk,sed,Regex,Bash,Shell,Awk,Sed,假设我有一个这样的句子 The quick, (brown, fox) jumps over, the (lazy, old, dog) 我想将括号内的所有逗号,替换为冒号:,但不应替换括号内的逗号。输出应该是 The quick, (brown: fox) jumps over, the (lazy: old: dog) 请注意,每个句子中逗号和括号的数量不是固定的。 如何使用shell相关工具(bash、sed、awk等)来实现这个结果 我试过使用sed的/[^(]*\([^)]*)\/

假设我有一个这样的句子

The quick, (brown, fox) jumps over, the (lazy, old, dog)
我想将括号内的所有逗号
替换为冒号
,但不应替换括号内的逗号。输出应该是

The quick, (brown: fox) jumps over, the (lazy: old: dog)
请注意,每个句子中逗号和括号的数量不是固定的。 如何使用shell相关工具(bash、sed、awk等)来实现这个结果


我试过使用sed的/[^(]*\([^)]*)\/\1/g;s/,/:/g'对所有匹配的组进行替换,但不确定如何将结果插回原始句子。

如果您的实际输入文件与显示的输入相同,则以下内容可能会对您的相同操作有所帮助

awk -F"[)(]" '{for(i=2;i<=NF;i+=2){gsub(/,/,":",$i);$i="("$i")"}} 1'  Input_file

使用步骤2递增循环的好主意!然而,似乎产生了一些额外的空格,有什么办法可以避免吗?用
OFS=“”
解决了它,谢谢@etopylight,很高兴能帮到你。看到这个@etopylight了吗?你确定它能按预期工作吗?尝试将添加到测试字符串中。(只需将
sub
更改为
gsub
)@WiktorStribiżew Good catch!这是一个更健壮的解决方案,可以很好地处理未闭合的括号。
The quick,  (brown: fox)  jumps over, the  (lazy: old: dog)