I tried the following code to replace QQ
with ZZ
, but it doesn't do what I want:
var1=QQ
sed -i 's/$var1/ZZ/g' $file
However, this code does what I want:
sed -i 's/QQ/ZZ/g' $file
How do I use variables in sed
?
I tried the following code to replace QQ
with ZZ
, but it doesn't do what I want:
var1=QQ
sed -i 's/$var1/ZZ/g' $file
However, this code does what I want:
sed -i 's/QQ/ZZ/g' $file
How do I use variables in sed
?
The shell is responsible for expanding variables. When you use single quotes for strings, its contents will be treated literally, so
sed
now tries to replace every occurrence of the literal$var1
byZZ
.Using double quotes
Use double quotes to make the shell expand variables while preserving whitespace:
When you require the quote character in the replacement string, you have to precede it with a backslash which will be interpreted by the shell. In the following example, the string
quote me
will be replaced by"quote me"
(the character&
is interpreted bysed
):Using single quotes
If you've a lot shell meta-characters, consider using single quotes for the pattern, and double quotes for the variable:
Notice how I use
s,pattern,replacement,
instead ofs/pattern/replacement/
, I did it to avoid interference with the/
in\0/
.Example
The shell then runs the above command
sed
with the next arguments (assumingpattern=bert
andfile=text.txt
):If
file.txt
containsbert
, the output will be:We can use variables in
sed
using double quotes:If you have a slash
/
in the variable then use different separator, like below:To expand (pun intended) on @mani's answer,
perl
|
may appear in your variable's value as well, so don't be scared to try other delimiters