Armen Yeganyan Armen Yeganyan - 1 year ago 71
Linux Question

Text manipulation with bash

I have bash variables defined in some file:

VAR1=....
VAR2="some value"
VAR3=....
....


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.

EDIT:

Expected output is:

VAR1=....
VAR2="another value"
VAR3=....
NEW_VAR=....
....

Answer Source

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

#!/bin/bash

#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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download