使用变量替换 shell 脚本中的字符串 [英] Replace a string in shell script using a variable
问题描述
我正在使用以下代码替换字符串在 shell 脚本中.
I am using the below code for replacing a string inside a shell script.
echo $LINE | sed -e 's/12345678/"$replace"/g'
但它被替换为 $replace
而不是那个变量的值.
but it's getting replaced with $replace
instead of the value of that variable.
谁能告诉我出了什么问题?
Could anybody tell what went wrong?
推荐答案
如果你想解释 $replace
,你不应该使用单引号,因为它们会阻止变量替换.
If you want to interpret $replace
, you should not use single quotes since they prevent variable substitution.
试试:
echo $LINE | sed -e "s/12345678/${replace}/g"
成绩单:
pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _
请注意确保 ${replace}
没有任何对 sed
有意义的字符(例如 /
)因为除非逃脱,否则会引起混乱.但是,如果如您所说,您将一个数字替换为另一个数字,那应该没有问题.
Just be careful to ensure that ${replace}
doesn't have any characters of significance to sed
(like /
for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.
这篇关于使用变量替换 shell 脚本中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!