Find and replace variables containing non-escaped

2019-05-11 15:33发布

问题:

I can use this, to find all instances of "fly" and replace it with "insect" in my file:

sed -i 's/fly/insect/g' ./animals.txt

How can I find a BASH variable and replace it with another BASH variable? E.g.:

name=$(echo "fly")
category=$(echo "insect")
sed -i 's/$name/$category/g' ./animals.txt

Update:

I am using GNU sed version 4.2.1. When I try the solutions below, it reports this error:

sed: -e expression #1, char 73: unknown option to `s'

Update:

I discovered why the error is coming up. $category frequently contains lots of symbols (e.g. "/", "$", "@", "!", brackets, etc.).

ame=$(echo "fly")
category=$(echo "in/sect")
sed -i "s/$name/$category/g" ./animals.txt

The above code will create the same error:

sed: -e expression #1, char 7: unknown option to `s'

Is there a way to let sed complete the replaces, even when it encounters these symbols?

回答1:

Using double quotes

Use double quotes to make the shell expand variables while keeping whitespace:

sed -i "s/$name/$category/g" ./animals.txt

Note: if you need to put backslashes in your replacement (e.g. for back references), you need double slashes (\& contains the pattern match):

Using single quotes

If you've a lot shell meta-characters, you can do something like this:

sed -i 's/'$pattern'/'$category'/g' ./animals.txt

I discovered why the error is coming up. $category frequently contains lots of symbols (e.g. "/", "$", "@", "!", brackets, etc.).

If the substitution or replacement portion contains characters like / then we can use different sets of sed delimiters. You can use something like - @ % , ; : | _ etc. any character that does not happen to occur in your substitution and replacement.



回答2:

Use double-quotes so the shell will interpolate your variables:

sed -i "s/$name/$category/g" ./animals.txt


回答3:

Use double quotes:

sed -i "s/$name/$category/g" ./animals.txt


标签: bash sed replace