繁体   English   中英

使用sed仅查找和替换字符串中的数字和第3个数字

[英]Find and Replace only numbers and 3rd number in the string using sed

在一个巨大的文件中,我有类似的端口号

"port": "7733",
"port": "7734",
"port": "7631",
"port": "7833",
"port": "7835",
"port": "7335",
"port": "9834",

我只需要使用sed用5替换(仅第3个数字)3。 预期的结果应该像

"port": "7753",
"port": "7754",
"port": "7651",
"port": "7853",
"port": "7855",
"port": "7355",
"port": "9854",

我努力了

sed -E 's/[0-9][0-9]3[0-9]+/[0-9][0-9]5[0-9]/g'

但这会将所有数字替换为[0-9] [0-9] 5 [0-9]。

请让我知道如何使用sed

sed允许您将与正则表达式匹配的文本保存为组,以备后用。 此解决方案保存两组: 3之前的数字和3之后的数字。 因此,替换文本由第一组表示为\\1 ,数字5和第二组表示为\\2 从而:

$ sed -E 's/([0-9][0-9])3([0-9]+)/\15\2/g' file
"port": "7753",
"port": "7754",
"port": "7651",
"port": "7853",
"port": "7855",
"port": "7355",
"port": "9854",

如果您的数据包含4位数端口,则可以使用awk拆分字段并将其添加20:

$ awk 'BEGIN{FS=OFS="\""}{$4+=20}1' file
"port": "7753",
"port": "7754",
"port": "7651",
"port": "7853",
"port": "7855",
"port": "7355",
"port": "9854",

一旦输出看起来不错,您就可以重定向到另一个文件。 另外,如果您使用的是GNU awk v4.1或更高版本,则可以通过以下方式进行更改:

awk -i inplace 'BEGIN{FS=OFS="\""}{$4+=20}1' file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM