Home > database >  Modify values in conf file by using shell script
Modify values in conf file by using shell script

Time:08-08

I have shell script and as part of the script I want to update the a.conf file (it is configuration file) which includes key-value pair, I want to update the values of the key. Script ask user to input the values which I am storing into variables. How could I update the multiple values in below file by using those variables. I tried sed but not sure how to use it for only to modify value of a particular key

a.conf file

key1=value1
key2=value2

I tried below sed command but it is not updating the value of given key -

sed -i -e "s/\($key1 *= *\).*/\1$newvalue/" $CONFIG_FILE

Update

If I update above command by removing space between *=*\ then, newvalue get appended to existing value e.g. key1=value1newvalue

Not sure what I am missing here

CodePudding user response:

I found one way to modify values of a particular key in a given file of format of -

key1=value1
key2=value2

sed -i "s/key1.*/key1=$newvalue/" "$CONFIG_FILE"

CodePudding user response:

If you don't mind using awk and maybe a temporary file then you could do:

if awk '
    BEGIN {
        FS = OFS = "="
        for (i = 2; i < ARGC; i  = 2) {
            keys[ARGV[i]] = ARGV[i 1]
            ARGV[i] = ARGV[i 1] = ""
        }
    }
    NF >= 2 && match($1,/[^ =] /)) {
        k = substr($0,RSTART,RLENGTH)
        if ( k in keys )
            $0 = k "=" keys[k]
    }
    1
' "$CONFIG_FILE" key1 "new val1" key2 "new val2" > "$CONFIG_FILE.new"
then
    mv "$CONFIG_FILE.new" "$CONFIG_FILE"
fi

If your standard awk is actually a GNU awk >= 4.3 then you can use -i -inplace instead of if ...; then mv ...; fi:

awk -i inplace '...' "$CONFIG_FILE" key1 "new val1" key2 "new val2"

CodePudding user response:

Here I read the a.conf line-by-line and define the key and val as variables. The user is asked to input the values, which are replaced in the a.conf using sed.

#!/bin/bash

CONFIG_FILE=a.conf
cat $CONFIG_FILE | while read line; do
   echo "Processing line: $line"
   key=$(echo $line | awk -F= '{print $1}');
   read  -p "Enter value for $key " val < /dev/tty
   sed -ie "s/^$key=.*/$key=$val/" "$CONFIG_FILE"
done

Trial run:

$ cat a.conf
key1=value1
key2=value2

$ ./script.sh
Processing line: key1=value1
Enter value for key1 test1
Processing line: key2=value2
Enter value for key2 test2

$ cat a.conf
key1=test1
key2=test2
  • Related