in Blog Posts, Solution

Use a different delimiter in sed

Think about this, you want to replace “XXX” with a path like “/path/to/YYY” in a file.
Your file looks like this:

XXX
AAA
XXX

Your bash script looks like this:

NEW_PATH="/path/to/YYY"
VAR="XXX"
sed -e '{s/$VAR/$NEW_PATH/g}' your_file

Well, it won’t work, since single quotes ‘ will force bash to keep variables as-is.

Ok, we try to use double quotes ”

NEW_PATH="/path/to/YYY"
VAR="XXX"
sed -e "{s/$VAR/$NEW_PATH/g}" your_file

This one won’t work either.
It is ok for sed to not have the single quotes, the problem is
you have slash in your NEW_PATH variable, which is the default delimiter of sed.

This simple stuff took me about an hour :[

The solution is just use a different delimiter in sed.

NEW_PATH="/path/to/YYY"
VAR="XXX"
sed -e "{s@$VAR@$NEW_PATH@g}" your_file

Sometimes, you still want to use single quotes to keep your special symbols, such as ‘(‘ ‘)’
It is ok for your to mix quotes:

NEW_PATH="/path/to/YYY"
VAR="XXX"
sed -e '{s@\(.*\)@'"$NEW_PATH"'@g}' your_file

Write a Comment

Comment