Using a different separator than ‘/’ with sed

You probably know the ‘s’ (“substitute”) command that sed offers. But did you know you other character could be used as separator?

shell> echo "Hello World" | sed "s/World/Neo/"
Hello Neo
shell> echo "Hello World" | sed "s_World_Neo_"
Hello Neo

That’s right, ‘_’ can be used instead of ‘/’. In this case, ‘/’ become a normal character and does’t have to be escaped anymore.
It is very useful when working with URLs:

shell> echo "http://hostA/pathA/" | sed "s_hostA/pathA_hostB/pathB_"
http://hostB/pathB/

Even the space character (‘ ‘) is suitable; just don’t forget the one at the end of the command.

shell> echo "Hello World" | sed "s World Neo "
Hello Neo

The official documentation formalises this behavior:

The / characters may be uniformly replaced by any other single character within any given s command.
The / character (or whatever other character is used in its stead) can appear in the regexp or replacement only if it is preceded by a \ character.

Leave a Reply

Your email address will not be published. Required fields are marked *