Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the command mean? sed 's,^.*/,,'

Tags:

sed

It's really un-usual using of sed for me. I'm used to have 's/pattern1/pattern2/g'.

Can someone help me to explain it?
The input string is just like the following:

path1/path2/path3/fileA path1/path2/path3/fileB path1/path2/path3/fileC

the output is fileA fileB fileC.

like image 399
user2955454 Avatar asked Dec 28 '25 16:12

user2955454


1 Answers

It's a substitute command using ',' instead of '/' as a separator - probably because there's a '/' in the pattern. It's equivalent to

s/^.*\///

which says remove everything from beginning of line to the last forward slash.

When you use 's' the next character is used as the separator. So you could also write it as

s!^.*/!!
s@^.*/@@

etc

using a different separator saves you having to escape instances of the separator in your patterns.

Your example input:

path1/path2/path3/fileA

'^' means 'from the start of the string', '.*' means 'match anything' which is 'greedy' so it tries to match as much of the string as possible. '.*/' tries to greedily match anything so long as it's followed by a '/'. Because it's greedy, that includes other slashes. so it matches path1/path2/path3/. The replacement pattern is '', i.e. nothing, so it effectively removes everything from the start of the string to the last '/', leaving just fileA

TL;DR: It means "remove path information and leave just the filename"

like image 143
kfsone Avatar answered Jan 01 '26 20:01

kfsone