Home > Software design >  How do use correct variable for find and replace?
How do use correct variable for find and replace?

Time:04-16

I want to replicate Wprdpress db name and username in the file for that I have blow code.

newdbname=${UN:0:8}"_wpdb"
newdbuser=${UN:0:8}"_wpuser"

DB_NAME=`cat wp-config.php | grep DB_NAME | cut -d \' -f 4`
DB_USER=`cat wp-config.php | grep DB_USER | cut -d \' -f 4`
sed -i "s/$DB_NAME/$newdbname/g" "$file"
sed -i "s/$DB_USER/$newdbuser/g" "$file"

But what happen here is, if the db name and username is same, in that case sed uses the username as db name and I get output like this

define( 'DB_NAME', 'domain_wpuserdb' );
define( 'DB_USER', 'domain_wpuserdb' );

expected result

define( 'DB_NAME', 'domain_wpdb' );
define( 'DB_USER', 'domain_wpuser' );

I have tried sed and perl as well

perl -i -pe "s/$DB_NAME/$newdbname/g" "$file"
perl -i -pe "s/$DB_USER/$newdbuser/g" "$file"

but I am get same result. what changes should I make to correct this?

CodePudding user response:

You can use an address prefix before the sed command to match a particular line to operate on. So you only replace the DB name in the DB_NAME line, and replace the username in the DB_USER line.

There's also no need for two sed commands, you can execute multiple operations in a single command by using multiple -e options.

sed -i -e "/DB_NAME/s/'$DB_NAME'/'$newdbname'/" -e "/DB_USER/s/'$DB_USER'/'$newdbuser'/" "$file"
  • Related