2

Let's say I have a wp-config.php like so:

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

In my bash script I have a construct similar to:

#!/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"

It doesn't work however. How could I edit (using sed) the variables db_name, user & pass in test.txt given that these variables would typically be unknown in advance?

1
  • Have you considered using m4 instead of sed? See man m4. Feb 19, 2017 at 13:45

1 Answer 1

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
1
  • Thanks Rakesh. Use -i flag to edit the actual file :).
    – cookie
    Feb 19, 2017 at 15:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .