alphanumeric
alphanumeric

Reputation: 19329

How to use sed to replace variable value declared in a text file

I would like to edit the /etc/environment file to change the MY_VARIABLE from VALUE_01 to VALUE_02.

Here is the context of the /etc/environment file:

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
JAVA_HOME="/usr/java/jdk8/jdk1.8.0_92-1"
MY_VARIABLE=VALUE_01

Ideally I would like to use sed command to edit it, for example (please note it is not working command):

sed -e 'MY_VARIABLE=VALUE_02' -i /etc/environment

How can I achieve it?

Upvotes: 0

Views: 646

Answers (2)

Shawn
Shawn

Reputation: 52364

Instead of trying to use sed -i and hoping your version of sed implements that option and working out if it takes a mandatory argument or not (I have a feeling you're not using GNU sed like the linux tag suggests you should be), just use ed to edit files in scripts.

ed -s /etc/environment <<EOF
/^MY_VARIABLE=/c
MY_VARIABLE=VALUE_02
.
w
EOF

changes the first line starting with MY_VARIABLE= to the given new text, and writes the file back to disk.

Upvotes: 1

Quas&#237;modo
Quas&#237;modo

Reputation: 4004

sed -- 's/MY_VARIABLE=.*/MY_VARIABLE=VALUE_02/' /etc/environment

Once you check it works, add the -i option:

sed -i -- 's/MY_VARIABLE=.*/MY_VARIABLE=VALUE_02/' /etc/environment

You will probably need root access.

Upvotes: 1

Related Questions