简体   繁体   English

使用字符作为bash中的分隔符获取最后一个字符串

[英]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] 类似Python的string.split('/')[ - 1]

Pure bash solution: 纯粹的bash解决方案:

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

Using sed : 使用sed

$ echo "silly/horse/fox/lion" | sed 's#.*/##'
lion

awk to the rescue: awk救援:

$ 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. 因为$NF指的是最后一个字段。

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

or 要么

grep -o "[^/]*$"  

or 要么

sed 's#.*/##'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM