不幸的是,sed 无法稳健地处理可能包含对 sed 和 shell 来说“特殊”的各种字符的变量。为此,您需要使用 awk,例如使用 GNU awk 进行 gensub():
gawk -v pass="$PASS" '{$0=gensub(/(\[\047password\047] = \")/,"\\1"pass,"g")}1' file
当 PASS 包含正斜杠但 awk 不在乎时,请参阅下面的 sed 如何失败:
$ 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