如何在shell中拆分字符串并获取最后一个字段 [英] How to split a string in shell and get the last field
本文介绍了如何在shell中拆分字符串并获取最后一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有字符串 1:2:3:4:5
并且我想获取它的最后一个字段(在本例中为 5
).我如何使用 Bash 做到这一点?我试过cut
,但是我不知道如何用-f
指定最后一个字段.
Suppose I have the string 1:2:3:4:5
and I want to get its last field (5
in this case). How do I do that using Bash? I tried cut
, but I don't know how to specify the last field with -f
.
推荐答案
您可以使用字符串运算符:
$ foo=1:2:3:4:5
$ echo ${foo##*:}
5
这会贪婪地修剪从前面到:"的所有内容.
This trims everything from the front until a ':', greedily.
${foo <-- from variable foo
## <-- greedy front trim
* <-- matches anything
: <-- until the last ':'
}
这篇关于如何在shell中拆分字符串并获取最后一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文