Replace a string in shell script using a variable

2018-12-31 07:41发布

I am using the below code for replacing a string inside a shell script.

echo $LINE | sed -e 's/12345678/"$replace"/g'

but it's getting replaced with $replace instead of the value of that variable.

Could anybody tell what went wrong?

标签: unix shell sed
9条回答
ら面具成の殇う
2楼-- · 2018-12-31 08:10

I prefer to use double quotes , as single quptes are very powerful as we used them if dont able to change anything inside it or can invoke the variable substituion .

so use double quotes instaed.

echo $LINE | sed -e "s/12345678/$replace/g"
查看更多
梦醉为红颜
3楼-- · 2018-12-31 08:13

Found a graceful solution.

echo ${LINE//12345678/$replace}
查看更多
裙下三千臣
4楼-- · 2018-12-31 08:18

If you want to interpret $replace, you should not use single quotes since they prevent variable substitution.

Try:

echo $LINE | sed -e "s/12345678/\"${replace}\"/g"

assuming you want the quotes put in. If you don't want the quotes, use:

echo $LINE | sed -e "s/12345678/${replace}/g"

Transcript:

pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _

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.

查看更多
无与为乐者.
5楼-- · 2018-12-31 08:20

you can use the shell (bash/ksh).

$ var="12345678abc"
$ replace="test"
$ echo ${var//12345678/$replace}
testabc
查看更多
忆尘夕之涩
6楼-- · 2018-12-31 08:24
echo $LINE | sed -e 's/12345678/'$replace'/g'

you can still use single quotes, but you have to "open" them when you want the variable expanded at the right place. otherwise the string is taken "literally" (as @paxdiablo correctly stated, his answer is correct as well)

查看更多
初与友歌
7楼-- · 2018-12-31 08:27

Single quotes are very strong. Once inside, there's nothing you can do to invoke variable substitution, until you leave. Use double quotes instead:

echo $LINE | sed -e "s/12345678/$replace/g"
查看更多
登录 后发表回答