Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables in a command in sed?

Tags:

unix

sed

I have abc.sh:

exec $ROOT/Subsystem/xyz.sh

On a Unix box, if I print echo $HOME then I get /HOME/COM/FILE.

I want to replace $ROOT with $HOME using sed.

Expected Output:

exec /HOME/COM/FILE/Subsystem/xyz.sh

I tried, but I'm not getting the expected output:

sed  's/$ROOT/"${HOME}"/g' abc.sh > abc.sh.1

Addition:

If I have abc.sh

exec $ROOT/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh

then with

sed "s|\$INSTALLROOT/|${INSTALLROOT}|" abc.sh

it is only replacing first $ROOT, i.e., output is coming as

exec /HOME/COM/FILE/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh
like image 678
VJS Avatar asked Oct 03 '13 06:10

VJS


People also ask

Can we use variables in sed command?

The shell is responsible for expanding variables. When you use single quotes for strings, its contents will be treated literally, so sed now tries to replace every occurrence of the literal $var1 by ZZ .

How do you call a variable in sed command?

First, choose a delimiter for sed's s command. Let's say we take '#' as the delimiter for better readability. Second, escape all delimiter characters in the content of the variables. Finally, assemble the escaped content in the sed command.

How do you replace a variable in a file using sed?

How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.


3 Answers

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh
like image 63
devnull Avatar answered Oct 02 '22 12:10

devnull


This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
like image 28
potong Avatar answered Oct 02 '22 10:10

potong


This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile
like image 45
pratibha Avatar answered Oct 02 '22 11:10

pratibha