This question already has an answer here:

I am trying to replace a word in a text file with the current username. I am trying to do this with "sed" using $USER, but it keeps actually writing "$USER" in the text file instead of my username.

sed -i 's/test/$USER/g' ~/.gtkrc-2.0

Can anyone help? Thank you in advance.

marked as duplicate by kos, Ravan, Eric Carvalho, Charles Green, hg8 Dec 31 '15 at 8:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Variables are not expanded when put inside single quotes. Use double quotes instead:

sed -i "s/test/"$USER"/g" ~/.gtkrc-2.0

Also it is a good idea to take a backup while modifying file in place:

sed -i.bak "s/test/"$USER"/g" ~/.gtkrc-2.0

The original file will be kept as ~/.gtkrc-2.0.bak, the modified one will be ~/.gtkrc-2.0.

  • Silly me! I tried it with double quotes earlier, but I didn't realize I needed quotes around the variable as well. Thank you for this answer, I hope it helps others too. – ovine Dec 29 '15 at 1:21
  • I thought the explanation given to you here just yesterday would have been useful as well: askubuntu.com/a/714077/248158 – DK Bose Dec 29 '15 at 1:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.