Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I try the fallowing code and it does nothing

sed -i 's/$var1/ZZ/g' $file

However this code replaces QQ with ZZ

sed -i 's/QQ/ZZ/g' $file

How to use variables in sed?

share|improve this question
see my answer in this post of yours – ata Nov 7 '11 at 16:54
up vote 85 down vote accepted

The shell is responsible for expanding variables. If you use single quotes for strings, the contents will be treated literally, so sed now tries to replace every occurrence of the literal $var1 by ZZ.

Using double quotes

Use double quotes to make the shell expand variables while keeping whitespace:

sed -i "s/$var1/ZZ/g" "$file"

Beware: if you need to put backslashes in your replacement (e.g. for back references), you need double slashes (\& contains the pattern match):

sed -i "s/quote me/\"\\&\"/" "$file"

Using single quotes

If you've a lot shell meta-characters, consider using single quotes for the pattern, and double quotes for the variable:

sed -i 's,'"$pattern"',Say hurrah to \&: \0/,' "$file"

Notice how I use s,pattern,replacement, instead of s/pattern/replacement/, I did it to avoid interference with the / in \0/.


The shell then runs the command sed with the next arguments (assuming pattern=bert and file=text.txt):

s,bert,Say hurrah to \&: \0/,'

If file.txt contains bert, it will become:

Say hurrah to bert: \0/
share|improve this answer
How would one pass the "/g" option using this comma separated form? – blong Apr 1 '14 at 13:55
@b.long It's a g option, so you would pass s,foo,bar,g instead. – Lekensteyn Apr 1 '14 at 14:32
Thank you very much! :) – blong Apr 1 '14 at 14:56

We can use variable in sed but with double quote:

sed -i "s/$var/r_str/g" file_name

If you have a slash / in the variable then use different separator, like below:

sed -i "s|$var|r_str|g" file_name
share|improve this answer
+1 for an easier solution :) – Anonymous Platypus May 13 '15 at 10:32
Good alternative using | for the separator it worked for me! Thanks Mani – Pavan WLA Aug 18 '15 at 10:28

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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