Vicky Dev
Vicky Dev

Reputation: 2173

Force sed to replace the matching line only once in the target file

I have following script to replace the specified key-value pairs in PHP INI Configuration file:

iniConfigs='memory_limit=3G
short_open_tag=On
post_max_size=512M
max_input_time=3600
max_execution_time=21600
upload_max_filesize=128M
extension_dir="C:\\PHPs\\PHP7032\\ext"'

while IFS= read -r line
do
    key=$(awk -F\= '{print $1}' <<< $line)
    sed -i "s/^\($key\).*/\1 ${line}/" php.ini
done <<< "$iniConfigs"

Now here is the problem with sed, it doesn't exactly find the line starting with the matching key and replace it with corresponding line as expected, which results into something like below in the php.ini:

short_open_tag short_open_tag=On
...
max_execution_time max_execution_time=21600

instead of,

short_open_tag=On
...
max_execution_time=21600

Why sed doesn't exactly replace the string as expected ?

Upvotes: 1

Views: 192

Answers (1)

codeforester
codeforester

Reputation: 42999

You have \1 in the replacement pattern. You don't need that because $line already has the key. This will do:

while IFS= read -r line
do
    key=$(awk -F\= '{print $1}' <<< $line)
    sed -i "s/^$key.*/$line/" php.ini
done <<< "$iniConfigs"

This code will break if your content has any characters than can confuse sed. For example, /.

Upvotes: 1

Related Questions