不幸的是,sed無法穩健地處理可能包含對sed和shell「特殊」的各種字符的變量。你需要爲此使用awk,例如與GNU AWK的gensub():
gawk -v pass="$PASS" '{$0=gensub(/(\[\047password\047] = \")/,"\\1"pass,"g")}1' file
查看如何SED以下時失敗PASS包含正斜槓,但awk並不在意:
$ cat file
The string: ['password'] = ""; needs to be replaced
$ PASS='foo'
$ awk -v pass="$PASS" '{$0=gensub(/(\[\047password\047] = \")/,"\\1"pass,"g")}1' file
The string: ['password'] = "foo"; needs to be replaced
$ sed "s/\(\['password'\] = \"\)\(\";\)/\1$PASS\2/g" file
The string: ['password'] = "foo"; needs to be replaced
$ PASS='foo/bar'
$ awk -v pass="$PASS" '{$0=gensub(/(\[\047password\047] = \")/,"\\1"pass,"g")}1' file
The string: ['password'] = "foo/bar"; needs to be replaced
$ sed "s/\(\['password'\] = \"\)\(\";\)/\1$PASS\2/g" file
sed: -e expression #1, char 38: unknown option to `s'
您需要使用\047
或其他方法(如果您願意,可以使用'"'"'
)代表單引號分隔的awk腳本中的單引號。
在沒有gensub awks()你只需要使用GSUB()代替:
awk -v pass="$PASS" '{pre="\\[\047password\047] = \""; gsub(pre,pre pass)}1' file
接受的答案實際上並不具有任意字符串的工作 - 事實上,惡意密碼可能結束的運行sed命令(替換操作)並啓動另一個任意的操作,對用戶的選擇進行任何編輯,以便對您的配置文件進行編輯!請考慮awk答案,或http://mywiki.wooledge.org/BashFAQ/021 –