Armen Yeganyan Armen Yeganyan - 1 year ago 61
Linux Question

Text manipulation with bash

I have bash variables defined in some file:

VAR2="some value"

How can I change the value of some variable and add one more variable in the specific line? I need to do it in the single shell script.


Expected output is:

VAR2="another value"

Answer Source

I believe that the following code would achieve the results you want, if I understood your question correctly:


#change the value of a certain variable
sed -i -e 's/^VAR2=.*$/VAR2="another-value"/gi' /folder/file

#add a new variable to the variable declaration area, using one existing variable as a reference point
sed -i -e '/^VAR2=/i \NEW_VAR="another-value"' /folder/file

exit 0

That would substitute the value of a variable and add a new variable to the list using one existing variable as the reference point as to where to insert the new variable. This code would work in many Bash versions.