Using variables within sed

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Using variables within sed



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?





have you tried with $name ?
– Preuk
Apr 27 '15 at 13:31



$name





This should work! Do you use some type of exotic shell?
– hek2mgl
Apr 27 '15 at 13:35





that works great too, thank you
– rog
Apr 27 '15 at 13:48





possible duplicate of sed with & in variable
– NeronLeVelu
Apr 27 '15 at 14:02





possible duplicate of sed substitution with bash variables
– Etan Reisner
Apr 27 '15 at 14:43




1 Answer
1



The problem is that the bash shell does not do variable expansion within single quotes. For example:


bash


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):


sed


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.


/


sed



You should either sanitise your input data or use tools where the scope for attack is greatly reduced.





What would be the benefit of doing so? Except of giving the user the chance to inject shell commands when typing his name?
– hek2mgl
Apr 27 '15 at 13:32






thanks for quick response paxdiablo, worked perfectly
– rog
Apr 27 '15 at 13:37






@paxdiablo LOL! :D
– hek2mgl
Apr 27 '15 at 13:38





Exec=pantheon-terminal -e "bash /home/myname/folder/script.sh" this is part of a desktop launcher, if somebody else was to run my script on their pc, i needed a line of code in my script to change "myname" to the users name.
– rog
Apr 27 '15 at 13:44





it is a bash script, and the double quotes worked great, thanks
– rog
Apr 27 '15 at 13:49






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard