在 bash 脚本中使用 sed 替换未知字符串

在 bash 脚本中使用 sed 替换未知字符串

假设我有一个wp-config.php这样的:

define('DB_NAME', 'db_name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');

在我的 bash 脚本中,我有一个类似于以下的构造:

#!/usr/bin/bash

# Database config
echo -e "\ndatabase name: \c"
read DB_NAME
sed -i -e "s/define('DB_NAME', );/define('DB_NAME', $DB_NAME);/g" "C:/Apache24/htdocs/test.txt"

然而它不起作用。鉴于这些变量通常是事先未知的,我如何编辑(使用sed)变量db_name, user& ?passtest.txt

答案1

eval "`echo 'NL=qsq' | tr 'qs' '\047\012'`"; # newline
echo DB_NAME; read DB_NAME;
db_name_esc=$DB_NAME
db_name_esc=${db_name_esc//\\/\\\\\\\\}   # escape backslash
db_name_esc=${db_name_esc//\'/\\\\\'}     # escape single quote
db_name_esc=${db_name_esc//\"/\\\"}       # escape double quote
db_name_esc=${db_name_esc//&/\\&}         # escape & special to sed
db_name_esc=${db_name_esc//\//\\\/}       # escape / special to s///
db_name_esc=${db_name_esc//${NL}/\\${NL}} # esc literal newline for sed

# and then plug in your variables properly escaped for both PHP+sed
sed -e "
   s/\\(define('DB_NAME',\\).*/\\1 '$db_name_esc');/
" yourfile

相关内容