Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a substring from end in Bash [duplicate]

I have a string that looks like this:

hello/my/name/is/lebowski

I need to extract the part of the string after the last / (lebowski in this case). I need to do this is Bash. How do I achieve this? I could do this in Java or Python using regex functionalities, but I don't know how to the same through Bash commands.

Any help would be appreciated. Thanks!

like image 236
lebowski Avatar asked Apr 12 '26 15:04

lebowski


2 Answers

Generally, when you have text that looks like a directory path, the basename and dirname commands can come in handy. basename gives you the file's name without the leading path (lebowski in this case), and dirname gives you the directory name without the file (hello/my/name/is/ in this case).

Either way, these both spawn a subprocess. You can use variable substitution to get what you want, like so:

var="hello/my/name/is/lebowski"
name=${var##*/}

I recommend reading the section on substitutions in the bash manual for more information.

like image 153
Ron Avatar answered Apr 15 '26 04:04

Ron


With simple bash parameter substitution:

s="hello/my/name/is/lebowski"
echo ${s##*/}
lebowski

${var##Pattern} - Remove from $var the longest part of $Pattern that matches the front end of $var

like image 45
RomanPerekhrest Avatar answered Apr 15 '26 04:04

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!