Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace variables containing non-escaped characters with sed

Tags:

bash

replace

sed

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?

like image 624
Village Avatar asked Feb 03 '26 04:02

Village


1 Answers

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.

like image 164
jaypal singh Avatar answered Feb 05 '26 23:02

jaypal singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!