Take the 2-minute tour ×

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
add comment

1 Answer

up vote 30 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
add comment

Your Answer


