-1

I came across following snippets which talks about different ways to escape slashes:

echo '/dir1/dir2/usr/local/bin/dir3' | sed 's/\/usr\/local\/bin/\/common\/bin/' 
echo '/dir1/dir2/usr/local/bin/dir3' | sed 's_/usr/local/bin_/common/bin_' 
echo '/dir1/dir2/usr/local/bin/dir3' | sed 's:/usr/local/bin:/common/bin:'
echo '/dir1/dir2/usr/local/bin/dir3' | sed 's|/usr/local/bin|/common/bin|'

The output was:

/dir1/dir2/common/bin/dir3
/dir1/dir2/common/bin/dir3
/dir1/dir2/common/bin/dir3
/dir1/dir2/common/bin/dir3

My doubt is why there is no slash at the end of the last three approaches. I tried putting at the end of second one:

echo '/dir1/dir2/usr/local/bin/dir3' | sed 's/\/usr\/local\/bin/\/common\/bin/' 
echo '/dir1/dir2/usr/local/bin/dir3' | sed 's_/usr/local/bin_/common/bin_/' 
echo '/dir1/dir2/usr/local/bin/dir3' | sed 's:/usr/local/bin:/common/bin:'
echo '/dir1/dir2/usr/local/bin/dir3' | sed 's|/usr/local/bin|/common/bin|'

But got an error:

/dir1/dir2/common/bin/dir3
sed: -e expression #1, char 30: unknown option to `s'
/dir1/dir2/common/bin/dir3
/dir1/dir2/common/bin/dir3
Mahesha999
  • 22,693
  • 29
  • 116
  • 189

1 Answers1

0

What those snippets show is that you can use basically any character as a delimiter for the command. s is the command and the character afterwards is the delimiter.
It is used to separate the "options" for s from each other.

s takes three options, the thing that is to be replaced (a regex), the thing that it is replaced with (a string) and flags like g for example.
You added a / in the last place which is interpreted as a flag, but the / is not a valid flag. That is what is causing the error.

echo '/dir1/dir2/usr/local/bin/dir3' | sed 's_/usr/local/bin_/common/bin_/' 
                                            ^^^             ^^          ^^
                                            123             24          25
1: the command
2: the delimieter
3: the first option
4: the second option
5: the flag sed does not understand

When you use something that is not a slash as the delimiter, the slash does not have any special meaning to sed.

toydarian
  • 4,246
  • 5
  • 23
  • 35
  • 2
    I wouldn't call those "options"; the first one is a regular expression, and the second one the replacement, and neither is optional. Anything that comes after the closing delimiter is called "flag" (like `g` for global substitution, `p` to print the pattern space, `i` for case insensitive matching etc.) – Benjamin W. Sep 03 '20 at 12:43
  • I called it "option" because of the error message: `sed: -e expression #1, char 30: unknown option to 's'`. Good catch on the "flag", will add that. – toydarian Sep 03 '20 at 12:45