Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

unix - How to use variables in a command in 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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...