Bash脚本:如何在文件中替换文本?

3
我目前拥有:
echo -n "MySQL Database Name:  "; read MyVar; sed -i 's/database_name_here/$MyVar/g' config.php

它部分地起作用,提示我输入数据库名称。一旦输入,它会更新文件,但仍然将$MyVar放在输入的内容之前。

echo -n "MySQL Database Name:  "; read MyVar; echo "$Myvar"

^ 可以正常工作。

有什么想法吗?

更新:

echo -n MySQL Database Name: ; read MyVar; sed -i s/database_name_here/$MyVar/g config.php
# ////
echo -n MySQL Username: ; read usr; sed -i s/username_here/$usr/g config.php
# ////
echo -n MySQL Password: ; read blackberg; sed -i s/password_here/$blackberg/g config.php

如果只是在bash中一行代码,它可以工作并替换值。 但是当我有上述情况时,它部分地工作但将值替换为空白。 有什么提示吗?

附注:您可以使用 read -p "MySQL 数据库名称:" MyVar 并且去掉 echo 语句。 - chepner
已解决更新问题。我忘记在字符串上添加''标签。 '$blackberg' - Vernard
1个回答

4
sed -i "s/database_name_here/$MyVar/g" config.php

如果想让shell解释变量,需要使用双引号。


无论如何,请不要点击接受方案的按钮,以便其他人可以看到您的问题已解决。 - Etheryte

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接