How to use sed to replace a config file's variable?
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 matchTHISISMYVARIABLE[ ]*=
. ([ ]*
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.