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 by ZZ.
Use double quotes to make the shell expand variables while preserving whitespace:
sed -i "s/$var1/ZZ/g" "$file"
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 by sed):
sed -i "s/quote me/\"&\"/" "$file"
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 above 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, the output will be:
Say hurrah to bert: \0/
\\0 instead of \0, it should not be done when \0 is enclosed in single quotes. Otherwise sed will substitute the pattern for a literal \0 instead of the whole match.
– Lekensteyn
Aug 23 '18 at 17:20
# as a delimiter is possible too: sed -i -e 's#$HOME/$SOME_PATH#$HOME/$ANOTHER_PATH#g'
– vladkras
Apr 15 '19 at 10:38
sed 's/'"${foo}"'/replacement/'
– leetbacoon
Oct 04 '19 at 03:01
sed ':a;N;$!ba;s/UUID=[A-Fa-f0-9-]*/UUID='"${new_uuid}"'/2' </etc/fstab | sudo tee /etc/fstab2 > /dev/null
– Anton Samokat
Jan 14 '24 at 15:50
We can use variables in sed using double quotes:
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
/ in the variable => This saved me ! My variable is a url and it contains /. Switching to use | as separator fixed my issue
– sonlexqt
Sep 20 '18 at 04:39
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