I tried the following code to replace
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
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
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 -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
The shell then runs the above command
sed with the next arguments (assuming
-i s,bert,Say hurrah to &: \0/, text.txt
bert, the output will be:
Say hurrah to bert: \0/
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
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?