繁体   English   中英

sed regex 替换为数学和引用

[英]sed regex replace with mathematics and quotation

我想用正则表达式替换一些数字,然后用 sed 做一些数学运算,但是,我的解决方案丢失了原始引用,我已经检查了 echo 的参数并尝试使用 -E 但它不起作用,任何人都可以提供帮助?

源文件内容

cat f1.txt
<AB port="10000" address="0.0.0.0" adpcpu="1"/>

我的命令

sed -r 's/(.*)(port=\")([0-9]+)(\".*)/echo \"\1\2$((\3+50))\4\"/ge' f1.txt

结果

<AB port=10050 address=0.0.0.0 adpcpu=1/>

结果内容漏了引文

如果您使用p选项,您将看到问题:

$ sed -E 's/(.*)(port=\")([0-9]+)(\".*)/echo \"\1\2$((\3+50))\4\"/gpe' ip.txt
echo "<AB port="$((10000+50))" address="0.0.0.0" adpcpu="1"/>"
<AB port=10050 address=0.0.0.0 adpcpu=1/>

您可以使用单引号解决:

$ sed -E 's/(.*port=")([0-9]+)(.*)/echo \x27\1\x27$((\2+50))\x27\3\x27/pe' ip.txt
echo '<AB port="'$((10000+50))'" address="0.0.0.0" adpcpu="1"/>'
<AB port="10050" address="0.0.0.0" adpcpu="1"/>

$ sed -E 's/(.*port=")([0-9]+)(.*)/echo \x27\1\x27$((\2+50))\x27\3\x27/e' ip.txt
<AB port="10050" address="0.0.0.0" adpcpu="1"/>

我还建议改用perl

$ perl -pe 's/port="\K\d+/$&+50/e' ip.txt
<AB port="10050" address="0.0.0.0" adpcpu="1"/>

使用 awk,而不是 sed:

$ awk -F'"' '{$2 += 50; print}' OFS='"' f1.txt
<AB port="10050" address="0.0.0.0" adpcpu="1"/>

使用"作为输入 ( -F'"' ) 和输出 ( OFS='"' ) 的字段分隔符。将 50 添加到第二个字段并打印结果。

如果您的文件包含其他类型的行,并且您只想将转换应用于匹配模式的行,则可以更具体。 例如,如果要搜索的模式是port=

$ awk -F'"' '/port=/{$2 += 50} {print}' OFS='"' f1.txt
A line of a different type
<AB port="10050" address="0.0.0.0" adpcpu="1"/>
Another line of a different type

这可能对你有用(GNU sed):

sed -E '/port="([0-9]+)"/{s//port="$((\1+50))"/;s/"/\\&/g;s/.*/echo "&"/e}' file

值得记住的是,当e标志与 sed 中的替换命令结合使用时,会评估整个模式空间。 因此,为了使用 echo 命令来插入 shell 算法,必须首先引用/转义模式空间中的任何双引号( s/"/\\\\&/g ),然后使用习语echo "pattern space" 。如这会产生一系列命令,必须使用大括号对命令进行分组。

NB 空正则表达式//重复最后一个正则表达式匹配(如果将空正则表达式传递给 s 命令也是如此)。

暂无
暂无

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

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