借助行號,將整行替換為包含檔案路徑的另一行

借助行號,將整行替換為包含檔案路徑的另一行

如何在檔案中用 New_String 取代 Old_String?

舊字串:

$result = $client->updateInventory("UpdateInventory.xml");
新字串:
$result = $client->updateInventory("/Desktop/new/UpdateInventory.xml");

名為 file1.txt 的檔案中的行號 = 5 中的 Old_String

我嘗試過的:

sed '5s/.*/'$result = $client->updateInventory("/Desktop/new/UpdateInventory.xml");'/' file1.txt

答案1

您可以使用以下命令來實現相同的效果

sed "5s:.*:'$'result = '$'client->updateInventory('/Desktop/new/UpdateInventory.xml');:g" filename | sed "s:'$':$:g" | tr "'" '"'

答案2

刪除內部單引號。它們結束了外部的命令,因此$result將擴展,並sed可能抱怨未完成的s命令。

相反,您可以使用命令的不同分隔符s,幾乎可以使用任何內容來代替斜線。所以

sed '5s_.*_$result = $client->updateInventory("/Desktop/new/UpdateInventory.xml")‌​;_' file1.txt

就是你想要的。

答案3

另一種方法是使用c命令清除位址指定的行

$ seq 5 | sed '2c\
foobar'
1
foobar
3
4
5

$ # with GNU-sed, assuming \ is not first character
$ seq 5 | sed '2cfoobar'

s如果替換字串具有某些特殊字符,則和命令c都會出現問題,例如:

$ seq 3 | sed '2s/.*/abc&xyz/'
1
abc2xyz
3
$ seq 3 | sed '2cabc\tabc'
1
abc     abc
3

處理這個問題的一個可靠方法是使用r命令

$ echo 'foo&\t\n\1///\\xyz' > f1
$ seq 3 | sed -e '2rf1' -e '2d'
1
foo&\t\n\1///\\xyz
3

答案4

使用 awk 指令也可以達到結果


awk  ‘NR==5 {gsub(".*","$result = $client->updateInventory(/Desktop/new/UpdateInventory.xml);",$0);print $0}' filename| sed 's/(/&"/g' | sed 's/)/"&/g'

相關內容