sed + 如何使用 sed/awk/other 用括号替换数字

sed + 如何使用 sed/awk/other 用括号替换数字

我们希望复发,[1023,1024,1022]如以下文件中所述,[1022]

more file.exm

{"topic":"nj_hgf_dfgef","partition":0,"replicas":[1023,1024,1022]},
{"topic":"nj_hgf_dfgef","partition":1,"replicas":[1024,1022,1023]},
{"topic":"nj_hgf_dfgef","partition":2,"replicas":[1022,1023,1024]},

预期输出

{"topic":"nj_hgf_dfgef","partition":0,"replicas":[1022]},
{"topic":"nj_hgf_dfgef","partition":1,"replicas":[1022]},
{"topic":"nj_hgf_dfgef","partition":2,"replicas":[1022]},

我们尝试

 sed -i s'/[0-9],[0-9],[0-9]/[1022]/g'  file.exm

但没有成功

答案1

尝试

sed -e 's/[0-9]\{4\},[0-9]\{4\},[0-9]\{4\}/1022/'

在哪里

  • \{4\}恰好发生了 4 次。

https://www.gnu.org/software/sed/manual/html_node/Regular-Expressions.html

答案2

您的正则表达式不正确,因为您希望每次每个数字只有 1 位。请尝试以下方法:

sed -i s'/[0-9]+,[0-9]+,[0-9]+/1022/g'  file.exm

如果+不适用于您的 版本sed,请将其替换为*

sed -i s'/[0-9]*,[0-9]*,[0-9]*/1022/g'  file.exm

如果你想测试你的正则表达式,我建议你使用以下在线网站: https://regex101.com/

答案3

一个简单的awk解决方案:

$ awk  -F':' '{ print $1":"$2":"$3":[1022]}," }' file.exm
{"topic":"nj_hgf_dfgef","partition":0,"replicas":[1022]},
{"topic":"nj_hgf_dfgef","partition":1,"replicas":[1022]},
{"topic":"nj_hgf_dfgef","partition":2,"replicas":[1022]},
$

相关内容