read a string from its end to its start and stop when you find a specific character

How can I do this? Actually I have a file which contains a path
e.g.
/home/john/Music/hello.mp3
and I want to take only the filename (hello.mp3) So, I need to read the file from its end to its start till the character "/"
Is this possible?
Thanks, I am sure you'll not disappoint me here!
Oh, yes, you are the best!:b:

man basename (POSIX)

basename /home/john/Music/hello.mp3

THIS WAS FAAAAAAAAAAAAST

Assuming your file contains only one path:

basename $(cat file)

The fact that I am 3 years now to Unix and there are sooo many unknows commands to me is hilarious.

a='/home/john/Music/hello.mp3'; echo ${a##*/}

much faster than calling the external command basename

in general

{text#pattern} removes the shortest match of pattern from the front of text
{text##pattern} removes the longest match of pattern from the front of text
{text%pattern} removes the shortest match of pattern from the back of text
{text%%pattern} removes the longest match of pattern from the back of text

Mike

But 90% of people will have no idea what this thing does, while seeing "basename /some/path" you can at least guess. And when you want to be sure you just do "man basename" and everything is clear. Don't obfuscate when it is not nessesary...

1 Like

Funny, that's how I feel about most of the awk answers here. :eek:

But seriously, no harm in giving out a learning example when others have already given the quick-help example. I answered the general question in the title--works even if the character is not "/".

Mike

Maybe learning AWK would be of more benefit for you, than those parameter substitutions :). Besides, AWK is found on virtually any system (in one version or another), while those parameter substitutions are just BASH feature (I think).

The pattern, default, substitution, and counting parameter substitutions are part of POSIX and are fully implemented in Sh, Korn, and Bash. Bash adds the very powerful positional, replacement, prefix, and array substititions.

I would like to learn AWK and I'm sure I would benefit. I'm not sure the syntax is any less obfuscated.

Mike

---------- Post updated at 08:44 PM ---------- Previous update was at 02:51 PM ----------

Been studying AWK for about an hour. I think this is an AWK example

awk 'BEGIN { FS="/" }; { print $NF }'

Testing:
$ echo '/this/is/a/path/this_is_a_file' | awk 'BEGIN { FS="/" }; { print $NF }'
this_is_a_file

Also:

awk -F "/" '{ print $NF }'