I am trying to use a variable within sed but cant work it out. I have tried
read -p " enter your name" name
sed -i 's/myname/$name/g' file
But unfortunately it just replaces myname with "$name". Is there an alternative way?
I am trying to use a variable within sed but cant work it out. I have tried
read -p " enter your name" name
sed -i 's/myname/$name/g' file
But unfortunately it just replaces myname with "$name". Is there an alternative way?
The problem is that the bash
shell does not do variable expansion within single quotes. For example:
pax> name=paxdiablo
pax> echo 'Hello, $name, how are you?'
Hello, $name, how are you?
For simple cases like this, you can just use double quotes:
pax> echo "Hello, $name, how are you?"
Hello, paxdiablo, how are you?
Having said that, there are some serious concerns with just using arbitrary data expanded like this. A clever attacker could give a name containing characters that would cause your sed
to do things you may not want (via an injection attack):
pax@paxbox$ name='/; e printenv; echo '
pax@paxbox$ echo 'Hello, myname' | sed "s/myname/$name/"
LESSOPEN=| /usr/bin/lesspipe %s
USER=pax
: (lots of other stuff about my environment I don't want people to see)
HOSTTYPE=x86_64
/
Hello,
And it doesn't even have to be clever - anyone entering a name containing /
will almost certainly cause your sed
to fail.
You should either sanitise your input data or use tools where the scope for attack is greatly reduced.