How do use correct variable for find and replace?

Viewed 80

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?

3 Answers

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"

Following demo code demonstrates one of many ways to achieve desired result

use strict;
use warnings;
use feature 'say';

my $db_name = 'domain_wpdb';
my $db_user = 'domain_wpuser';

while( <DATA> ) {
    if( /^define\( 'DB_NAME'\, / ) {
        say "define( 'DB_NAME', '$db_name' );"
    } elsif( /^define\( 'DB_USER', / ) {
        say "define( 'DB_USER', '$db_user' );"
    } else {
        print;
    }
}

exit 0;

__DATA__

Some text to be re-printed

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

Some text to be re-printed

Output


Some text to be re-printed

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

Some text to be re-printed

Alter the code to while( <> ) { and run as script.pl wp-config.php > temp-config.php, then inspect that desired result achieved in temp-config.php and replace wp-config.php file on success.

To match a specific line to act on, add the address as a prefix as before the sed command also You Don't Need to use two Sed commands instead you can use like this

sed -i "/DB_NAME/s/\"$DB_NAME\"/\"$newdbname\"/;/DB_USER/s/\"$DB_USER\"/\"$newdbuser\"/" "$file"
Related