简体   繁体   中英

Find and Replace Define(Key,Value) in SED Linux

Currently I'm trying to create a bash script for replacing new values I generated.

These values were stored in constants.php :

-----------constant.php : start-------------------
                      :
        define('PASS1', 'ABCD');
        define('PASS2', '1234');
                      :
-----------constant.php : end---------------------

After running script, (using sed ) it should update the values of PASS1 and PASS 2 separately:

-----------constant.php : start-------------------
                      :
        define('PASS1', 'WXYZ');
        define('PASS2', '0987');
                      :
-----------constant.php : end---------------------

Is there a way I can find the KEY eg 'PASS1' and replace the values after the comma?

You can specify the occurrence with sed so sed "/PASS1/s/'[^']*'/'WXYZ'/2" matches any lines containing PASS1 and does the following substitution s/'[^']*'/'WXYZ'/2 which:

s/     # Substitute  
'      # Match a single quote
[^']*  # Match anything not a single quote 
'      # Match the closing single quote 
/      # Replace with 
'WXYZ' # The literal value
/2     # The 2 here matches the second quoted string, not the first.  

# First key 
$ sed "/PASS1/s/'[^']*'/'WXYZ'/2" file

        define('PASS1', 'WXYZ');
        define('PASS2', '1234');

# Second key
$ sed "/PASS2/s/'[^']*'/'0978'/2" file

        define('PASS1', 'ABCD');
        define('PASS2', '0978');

# In one go
$ sed "/PASS1/s/'[^']*'/'WXYZ'/2;/PASS2/s/'[^']*'/'0978'/2" file

        define('PASS1', 'WXYZ');
        define('PASS2', '0978');

You need replacement rules similar to this:

/'PASS1'/ s/, *'[^']*'/, 'WXYZ'/

Which finds a line containing the quoted PASS1 and replaces the next argument with the correct password. Writing such rules is tedious and error prone, so I prefer letting sed write them for me. So if the file key-value.txt contains:

PASS1 WXYZ
PASS2 0987

You can generate the replacement rules with:

<key-value.txt sed "s:\(.*\) \(.*\):/\1/ s/, *'[^']*'/, '\2'/:"

Output:

/'PASS1'/ s/, *'[^']*'/, 'WXYZ'/
/'PASS2'/ s/, *'[^']*'/, '0987'/

Pipe this into a second sed to make the actual replacement:

<key-value.txt sed "s:\(.*\) \(.*\):/\1/ s/, *'[^']*'/, '\2'/:" | sed -f - constants.php

Use the -i switch with the second sed to change constants.php "in-place".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM