簡體   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