-1

In the code base, there is a line:

echo x/y/z | sed 's%/[^/]*$%%'

It will remove the /z from the input string.

I can't quite understand it.

  • s is substitution
  • %/ is quoting /
  • [^/]*$ means matching any characters except / any times from the end of line

But what is %% here?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Joe
  • 3
  • 1
  • 1
    `%` is the delimiter, so substitute `/[^/]*` with nothing. The nothing is `%%` where nothing is between the delimiters. In other forms it is `s/find/replace/` –  May 11 '18 at 18:37
  • Possible duplicate of [How to use different delimiters for sed substitute command?](https://stackoverflow.com/questions/5864146/how-to-use-different-delimiters-for-sed-substitute-command) – Sundeep May 12 '18 at 03:48

1 Answers1

2

Here's info sed:

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.

So the % is just an arbitrary delimiter. The canonical delimiter is /, but that collides with your pattern which is also /.

In other words, %/ isn't an escaped /. They're independent characters.

The expression breaks down like this:

s              Replace
  %              Delimiter
    /[^/]*$        Search pattern
  %              Delimiter
                   Empty replacement string
  %              Delimiter

Which is completely analogous to a simple s/foo/bar/:

s              Replace
  /              Delimiter
    foo            Search pattern
  /              Delimiter
    bar            Replacement string
  /              Delimiter
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • It's not completely analogous, as the pattern from the question is anchored at the end of the line, so it'll remove everything from the last occurrence of `/` to the end of the line. A simple substitution would replace the first occurrence. – Benjamin W. May 11 '18 at 21:53