Daz Daz - 4 days ago 5
Linux Question

Replace the lines if one part of string matches using shell script

I have a file call

config.txt
which contains something like this.

[MS-SQL]
DRIVER : FreeTDS
SERVER : 138.23.21.45


What I need to do is, Whatever the string values which contains after
SERVER :
need be replaced with a content in a shell variable like
$SERVER_IP
.

Final
config.ini
need to be like this.
(consider bash shell variable consist some this like
$SERVER_IP=192.168.5.3
)

[MS-SQL]
DRIVER : FreeTDS
SERVER : 192.168.5.3

Answer

This will change the line:

sed -iE 's/(SERVER : )([0-9.]+)/\1'"$SERVER_IP"'/' config.txt

Description:

-i                    # write changes to the file "in place".
-E                    # Use extended regex (to avoid the need
                      # of backslash in `()`)
's/ … / … /'          # Use the substitute command.
(SERVER : )           # Match the string you need `SERVER : ` capturing it
                      # in the first group of parenthesis.
([0-9.]+)             # capture digits and dots in the second group.
/\1'"$SERVER_IP"'/'   # write the contents of the first group and  
                      # the value of the variable to the file.
config.txt            # name of the file.
Comments