How to use sed to replace a config file's variable?

53,965

Solution 1

You can try this sed:

sed -i.bak 's/^\(VAR5=\).*/\1VALUE10/' file

It gives:

VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE10
VAR6=VALUE6

Solution 2

Even though the answer has been added to the question. I spent some time on how it works, I would like add some facts and my version of the answer,

sed -i 's,^\(THISISMYVARIABLE[ ]*=\).*,\1'THISISMYVALUE',g' config.cfg

Explanation:

  • As a basic of sed 's/find_this/replace_with/', we are saying sed to search and replace. Also remember there are multiple other delimiters that we can use instead of /. Here , is used.
  • Here we find the line that matches ^\(THISISMYVARIABLE[ ]*=\).* . This means we are grouping the match THISISMYVARIABLE[ ]*= . ([ ]* to cover if there are any spaces after the key)
  • In replace section \1 is a back-reference. We are referencing the first group in the regular expression that we used for match.

Solution 3

You can say:

sed '/^VAR5=/s/=.*/=VALUE10/' filename

To make in the change to the file in-place, use the -i option:

sed -i '/^VAR5=/s/=.*/=VALUE10/' filename

Solution 4

sed '/\(^VAR5=\).*/ s//\1VALUE10/' YourFile

Under AIX/KSH

$ cat sample.txt
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE5
VAR6=VALUE6

$ sed '/\(^VAR5=\).*/ s//\1VALUE10/' sample.txt
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE10
VAR6=VALUE6

and for replacement in file

cat <> YourFile | sed '/\(^VAR5=\).*/ s//\1VALUE10/'

$ cat <> sample.txt | sed '/\(^VAR5=\).*/ s//\1VALUE10/'
$ cat sample.txt
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE10
VAR6=VALUE6

To be POSIX (on sed part, not cat) compliant (sed --posix on gnu sed and natively traditionnal sed on non linux system)

Share:
53,965
SomeGuyOnAComputer
Author by

SomeGuyOnAComputer

.

Updated on April 20, 2021

Comments

  • SomeGuyOnAComputer
    SomeGuyOnAComputer about 3 years

    I've been looking online for this answer and cannot seem to find it.

    I have a config file that contains:

    VAR1=VALUE1
    VAR2=VALUE2
    VAR3=VALUE3
    VAR4=VALUE4
    VAR5=VALUE5
    VAR6=VALUE6
    

    And I want to change VAR5's value from VALUE5 to VALUE10. Unfortunately, I do not know the value of VALUE5 so I cannot search for it. So basically I need to use sed (or whatever) to replace the value of VAR5 to another value.