Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11295

Get the last string using a character as a delimiter in 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]

Upvotes: 5

Views: 590

Answers (3)

devnull
devnull

Reputation: 123458

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

Upvotes: 9

Kent
Kent

Reputation: 195039

awk -F'/' '$0=$NF'

or

grep -o "[^/]*$"  

or

sed 's#.*/##'

Upvotes: 3

fedorqui
fedorqui

Reputation: 289565

awk to the rescue:

$ echo "silly/horse/fox" | awk -F"/" '{print $NF}'
fox
$ echo "silly/horse/fox/but/not/that/much" | awk -F"/" '{print $NF}'
much
$ echo "unicorn" | awk -F"/" '{print $NF}'
unicorn

As $NF refers to the last field.

Upvotes: 5

Related Questions