4

I saw a bash command sed 's%^.*/%%'

Usually the common syntax for sed is sed 's/pattern/str/g', but in this one it used s%^.* for the s part in the 's/pattern/str/g'.

My questions:
What does s%^.* mean?
What's meaning of %% in the second part of sed 's%^.*/%%'?

photon
  • 1,309
  • 2
  • 12
  • 13

2 Answers2

11

The % is an alternative delimiter so that you don't need to escape the forward slash contained in the matching portion.

So if you were to write the same expression with / as a delimiter, it would look like:

sed 's/^.*\///'

which is also kind of difficult to read.

Either way, the expression will look for a forward slash in a line; if there is a forward slash, remove everything up to and including that slash.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 2
    Yes. Additionnal note: it uses the *last* slash in the line. – kmkaplan Aug 18 '10 at 07:26
  • Also worth noting, it functions similarly to `basename` (without the suffix argument) except that it will remove everything if the string ends in a slash and `basename` won't. – Dennis Williamson Nov 23 '10 at 01:44
1

the usually used delimiter is / and the usage is sed 's/pattern/str/'.

At times you find that the delimiter is present in the pattern. In such a case you have a choice to either escape the delimiter found in the pattern or to use a different delimiter. In your case a different delimiter % has been used.

The later way is recommended as it keeps your command short and clean.

codaddict
  • 445,704
  • 82
  • 492
  • 529