簡體   English   中英

在bash中如何替換字符串變量,並將其設置為sed命令

[英]In bash how to replace string variable, and set it into sed command

在bash腳本文件中,我設置了一個這樣的變量:

    current_path=`pwd`
    sed -i "1s/.*/working_path='$current_path';/" file1.sh

我想運行這個腳本將file1.sh的第一行file1.shworking_path='$current_path'; ,但是current_path具有/並且在sed命令中, /是以sed替換模式預定義的。 我試過這個:

    current_path1="${current_path/\//\\\/}"

上面這行,我想將/ in變量current_path替換為\\/ ,然后將current_path1輸入到sed命令中,但也有錯誤。

你能給我一些建議嗎? 謝謝。

嘗試這個。

sed -i -e "1s@.*@working_path='$current_path';@" file1.sh

在替換命令中使用@而不是/

您可以為s///命令使用不同的分隔符:

current_path=`pwd`
sed -i "1s|.*|working_path='$current_path';|" file1.sh

但你不是真的在這里搜索和替換,你想插入新行並刪除舊行:

current_path=`pwd`
sed -i -e "1i\working_path='$current_path)';" -e 1d file1.sh

你真的在改變.sh文件的第一行嗎? 你是否刪除了she-bang線?

請在模式字符串的開頭添加“/”。 它用string替換所有模式匹配。

 current_path1="${current_path//\//\\\/}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM