An Environment variable is a dynamic-named value. Generally, these are variables are exported in a single terminal using a command shown below
or they are stored inside the bash files, so that they remain available in all the terminals once the file is sourced. If we want to change an environment variable we can simply change the above command’s value field and then source the file, but if we want to do that with the help of the sed command then we need to know a little bit about the sed command.
Let’s explore the sed command, which is short for stream editor. This command is used to perform different functions like find, replace, insert and many more on a particular file.
sed [OPTIONS]... [SCRIPT] [INPUTFILE...]
Considering we have a simple text file where we want to replace a string that is present in the file to another string, we can make use of the grep command in that case.
immukul@192 linux% cat somefile.txt this is a test file and it is used for testing and is not available for anything else so please stop asking, lionel messi
Now we want to replace the string “it” with “litt” in the above file. The command to do that is shown below −
sed ‘s/it/litt’ somefile.txt
immukul@192 linux% cat somefile.txt this is a test file and litt is used for testing and is not available for anything else so please stop asking, lionel messi
Now let’s see how to exchange an environment variable’s value inside a bash script with the help of the sed command.
There’s an environment variable TUTS whose value is equal to /Users. In order to change that value in a bash script, we can add these lines to the script.
Now if we run the above script, and type PPP, then instead of printing PPP back, we will be able to print the value of the environment variable.
immukul@192 linux-questions-code % ./sss.sh PPP /Users