Skip to content
shellhacks.dev
Text Processing

Match a Literal Slash in sed by Changing the Delimiter

Replace text that contains slashes by using another delimiter after s, such as a bar or a hash. A delimiter inside the pattern must be escaped, and then it means itself.

1 min read
Summarize in AI

A sed command that edits a path turns into a thicket of escaped slashes.

Shell
echo '/usr/local/bin' | sed 's/\/usr\/local/\/opt/'
echo '/usr/local/bin' | sed 's|/usr/local|/opt|'
echo '/usr/local/bin' | sed 's#/usr/local#/opt#'
echo 'a|b' | sed 's|a\|b|X|'
echo 'a|b' | sed -E 's,a|b,X,g'
Text
/opt/bin
/opt/bin
/opt/bin
X
X|X

The character right after s is the delimiter, and any character works, so s|/usr/local|/opt| and the hash form say the same as the version with every slash escaped, and are far easier to read. The catch is that the delimiter loses its normal meaning inside the pattern. In the fourth command the bar inside the pattern is escaped, so it is a literal bar and a|b became X; with -E and a comma as delimiter, the bar between the words is alternation and both words were replaced. See The s Command.

Pick a delimiter that cannot occur in the data, and note that some characters, such as a newline or a backslash, cannot be used. If the replacement comes from a shell variable, a delimiter inside the value still breaks the command, so escape the value or use another tool.

Taggedregextext
Share

More snippets

Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.