3

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!

lebowski
  • 1,031
  • 2
  • 20
  • 37

4 Answers4

4

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.

Ron
  • 1,989
  • 2
  • 17
  • 33
3

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

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2

Just like in ksh

    st='hello/my/name/is/lebowski'
    echo ${st##*/}

    lebowski
1
$ mystring='hello/my/name/is/lebowski'
$ echo ${mystring##*/}
lebowski
markp-fuso
  • 28,790
  • 4
  • 16
  • 36