简体   繁体   English

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

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

In a huge file i have port numbers like 在一个巨大的文件中,我有类似的端口号

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

I just have to replace(only 3rd number) 3 with 5 using sed. 我只需要使用sed用5替换(仅第3个数字)3。 the intended result should be like 预期的结果应该像

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

I have tried 我努力了

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

but this will replace all numbers to [0-9][0-9]5[0-9]. 但这会将所有数字替换为[0-9] [0-9] 5 [0-9]。

Please let me know how can we achieve using sed 请让我知道如何使用sed

sed allows you to save the text that matched a regex as a group to be used later. sed允许您将与正则表达式匹配的文本保存为组,以备后用。 This solution saves two groups: the numbers before the 3 and the numbers after. 此解决方案保存两组: 3之前的数字和3之后的数字。 The replacement text thus consists of the first group, denoted \\1 , the number 5 , and the second group, denoted \\2 . 因此,替换文本由第一组表示为\\1 ,数字5和第二组表示为\\2 Thus: 从而:

$ 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",

If you data contains 4 digit ports then using awk you can just split the field and add 20 to it: 如果您的数据包含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",

Once the output looks good, you can re-direct to another file. 一旦输出看起来不错,您就可以重定向到另一个文件。 Alternatively if you are using GNU awk v4.1 or later you can make changes in place by doing: 另外,如果您使用的是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