Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I try the fallowing code and it does nothing

var1=QQ
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 1

up vote 36 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/.

Example

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

-i
s,bert,Say hurrah to \&: \0/,'
text.txt

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? –  b.long Apr 1 at 13:55
1  
@b.long It's a g option, so you would pass s,foo,bar,g instead. –  Lekensteyn Apr 1 at 14:32
    
Thank you very much! :) –  b.long Apr 1 at 14:56
add comment

Your Answer

 
discard

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.