5

I know this has been asked before but I'm having trouble understanding the answers I've found. Basically I want to use sed -i 's/<string>/</some/directory>/g' file.txt and I can't find a straight answer on how to make </some/directory> not break up the sed syntax

8

sed allows several syntax delimiters, / being only the one most commonly used.

You can just as well say

sed -i 's,<string>,<some/directory>,g' file.txt

where the , now has the function usually performed by the /, thereby freeing the latter from its special meaning.

Note, however (as pointed out by @Jeff Schaller), that now the , must not appear in the file or directory name - and it is a valid character for filenames! This answer gives a good overview on how to proceed when applying sed to string with special characters.

| improve this answer | |
5

Replacing the delimiter with one that is known not to appear in the search or replace strings is a good option when you can find a delimiter that does not appear in them. I tend to use the plus sign, rather than a comma, but that's a matter of habit more than anything.

However, if you can't find a delimiter that doesn't appear in the string, there's always backslash-escaping:

sed -e 's/<string>/<some\/directory>/g' file.txt

The \ in front of the slash lets sed know that it's just a slash and not a delimiter.

| improve this answer | |
0

@AdminBee I have only seen the # used as delimiter so far, guess it appears less often in the patterns than a comma:

sed -i 's#<string>#<some/directory>#g' file.txt
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.