我有位分層問題,用sed將使用一個變數作為搜索字串和做多行。我可以做或做,但不能同時做。我正在處理一個看起來像這樣的 xml 檔案。
<tag property="search1">
string
</tag>
<tag property="search2">
string
</tag>
<tag property="search3">
string
</tag>
我正在嘗試使用腳本根據其前一行上的“搜索”字串的數量,將“字串”依次替換為另一個值。腳本會增加一個計數器來執行此操作。
如果“$n”已知,我可以在“search$n”之后找到并替換“string”:
$ sed '$!N;/search2/ s/\string/foo/;P;D' test
<tag property="search1">
string
</tag>
<tag property="search2">
foo
</tag>
<tag property="search3">
string
</tag>
我可以根據變數搜索替換字串:
$ n=2
$ sed "/search$n/ s/search/foo/" test
<tag property="search1">
string
</tag>
<tag property="foo2">
string
</tag>
<tag property="search3">
string
</tag>
但我一直無法弄清楚如何將兩者結合起來:
$ sed '$!N;/search$n/ s/\string/foo/;P;D' test
上述命令有效;因為它不會拋出錯誤,但它不會決議變數- 我試過轉義它,并將它放在雙引號或單引號中并轉義它們。允許我在 sed 中決議多行的引數似乎需要單引號,而在搜索欄位中讀取變數需要雙引號......
我在 OSX 上使用 gnu-sed。以下是我嘗試過的其他一些事情:
sed "/search$n/, 1s/string/foo/" test
sed '/search$n/, 1s/string/foo/' test
sed "/search$n/, 1s s/string/foo/" test
sed '/search$n/, 1 s/string/foo/' test
sed '' -e '/search$n/ {' -e 'n; s/string/foo/' -e '}' test
sed '' -e '/search$n/ {' -e 'n; s/.*/foo/' -e '}' test
sed '/search$n/!b;n;c/foo/' test
sed '' -e '/search$n/!b;n;string' test
sed '' -e "/search$n/ {' -e 'n; s/string/foo/' -e '}" test
sed '' -e "/search$n/ {' -e 'n; s/.*/foo/g' -e '}" test
sed '' -e "/search$n/ s/string/foo/" test
sed -e "/search$n/ s/string/foo/" test
sed "/search$n/ s/string/foo/" test
uj5u.com熱心網友回復:
您需要宣告n=2(not i=2),然后使用雙引號來允許變數擴展。
然而,你需要照顧$和!類的特殊猛砸。您可以使用
n=2
sed '$!'"N;/search$n/ s/string/foo/;P;D" test
輸出:
<tag property="search1">
string
</tag>
<tag property="search2">
foo
</tag>
<tag property="search3">
string
</tag>
這'$!'"N;/search$n/ s/string/foo/;P;D"是$! (無可變擴展支持)和N;/search$n/ s/string/foo/;P;D(有可變擴展支持)的串聯。
uj5u.com熱心網友回復:
這可能對你有用(GNU sed):
n=2
sed '/search'"$n"'/{n;s/string/foo/}' file
設定n為2。
匹配上search2,列印當前行并獲取下一行。
如果以下行包含stringreplace stringby foo。
以下行可能不包含string但包含search2,在這種情況下:
sed ':a;/search'"$n"'/{n;s/string/foo/;Ta}' file
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323964.html
