Find and replace variables containing non-escaped characters with sed

孤人 提交于 2020-01-02 08:29:39

问题


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


来源:https://stackoverflow.com/questions/8938571/find-and-replace-variables-containing-non-escaped-characters-with-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!