【问题标题】:sed regex replace with mathematics and quotationsed 正则表达式替换为数学和引用
【发布时间】:2021-07-30 03:18:15
【问题描述】:

我想用正则表达式替换一些数字,然后用 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/>

生成的内容错过了引用

【问题讨论】:

标签: regex sed


【解决方案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"/>

【讨论】:

    【解决方案2】:

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

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

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

    注意空正则表达式 // 重复上一次正则表达式匹配(如果将空正则表达式传递给 s 命令,则同样如此)。

    【讨论】:

      【解决方案3】:

      使用 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
      

      【讨论】:

        猜你喜欢
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2018-08-22
        • 2013-08-25
        • 1970-01-01
        • 2018-01-07
        相关资源
        最近更新 更多