Get last line using character as delimiter in bash

Now I have this:

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

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

So, something like "stupid / horse / fox / lion" will return me a "lion"

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

+4
source share
3 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 
+8
source

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 

How $NF relates to the last field.

+4
source
 awk -F'/' '$0=$NF' 

or

 grep -o "[^/]*$" 

or

 sed 's#.*/##' 
+2
source

Source: https://habr.com/ru/post/1493431/


All Articles