Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 313
SomeGuyOnAComputer Avatar asked Dec 13 '13 14:12

SomeGuyOnAComputer


People also ask

How do you replace a variable in a file using sed?

How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.

How do you replace something with sed?

Find and replace text within a file using sed command The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How replace config file in Linux?

To edit any config file, simply open the Terminal window by pressing the Ctrl+Alt+T key combinations. Navigate to the directory where the file is placed. Then type nano followed by the filename that you want to edit. Replace /path/to/filename with the actual file path of the configuration file that you want to edit.


2 Answers

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
like image 110
anubhava Avatar answered Oct 04 '22 06:10

anubhava


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.
like image 30
Kannan Ramamoorthy Avatar answered Oct 04 '22 06:10

Kannan Ramamoorthy