Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last string using a character as a delimiter in bash

Tags:

string

bash

Right now I have this:

echo "silly/horse/fox" | cut -d "/" -f3
fox

But I want to be able to get the last string no matter how many delimiters we have.

So something like "silly/horse/fox/lion" would return me "lion"

Something of an equivalent to Python's string.split('/')[-1]

like image 263
Stupid.Fat.Cat Avatar asked Dec 08 '22 14:12

Stupid.Fat.Cat


1 Answers

Pure bash solution:

$ foo="silly/horse/fox"
$ echo ${foo##*/}
fox
$ foo="silly/horse/fox/lion"
$ echo ${foo##*/}
lion

Using sed:

$ echo "silly/horse/fox/lion" | sed 's#.*/##'
lion
like image 85
devnull Avatar answered Dec 11 '22 12:12

devnull