假设我有字符串1:2:3:4:5,我想要得到它的最后一个字段(在本例中是5)。我如何使用Bash做到这一点?我试过cut,但我不知道如何用-f指定最后一个字段。


当前回答

这里有很多很好的答案,但我仍然想用basename来分享这个:

 basename $(echo "a:b:c:d:e" | tr ':' '/')

然而,如果字符串中已经有一些'/',它将失败。 如果斜杠/是你的分隔符,那么你就必须(也应该)使用basename。

这不是最好的答案,但它只是展示了如何创造性地使用bash命令。

其他回答

假设使用相当简单(例如,没有转义分隔符),您可以使用grep:

$ echo "1:2:3:4:5" | grep -oE "[^:]+$"
5

分解-找到行($)末尾的所有字符,而不是分隔符([^:])。-o只打印匹配的部分。

对于那些熟悉Python的人来说,https://github.com/Russell91/pythonpy是解决这个问题的一个不错的选择。

$ echo "a:b:c:d:e" | py -x 'x.split(":")[-1]'

将stdin的每一行都视为x。

使用该工具,可以很容易地编写应用于输入的python代码。

编辑(2020年12月): Pythonpy不再在线。 这里有一个替代方案:

$ echo "a:b:c:d:e" | python -c 'import sys; sys.stdout.write(sys.stdin.read().split(":")[-1])'

它包含更多的样板代码(即sys.stdout.read/write),但只需要来自python的STD库。

使用sed:

$ echo '1:2:3:4:5' | sed 's/.*://' # => 5

$ echo '' | sed 's/.*://' # => (empty)

$ echo ':' | sed 's/.*://' # => (empty)
$ echo ':b' | sed 's/.*://' # => b
$ echo '::c' | sed 's/.*://' # => c

$ echo 'a' | sed 's/.*://' # => a
$ echo 'a:' | sed 's/.*://' # => (empty)
$ echo 'a:b' | sed 's/.*://' # => b
$ echo 'a::c' | sed 's/.*://' # => c
$ echo "a b c d e" | tr ' ' '\n' | tail -1
e

只需将分隔符转换为换行符,并选择尾为-1的最后一个条目。

对不起,我不能评论,但在这里; 来自@mateusz-piotrowski @user3133260的答案,

回声“e b: c: d::::::“| tr ':' ' ' | xargs | tr ' ' ' \ n ' |尾1

首先,tr ':' ' ' ->将':'替换为空格

然后,用xargs修整

之后,tr ' ' '\n' ->将保留的空格替换为换行符

最后,tail -1 ->得到最后一个字符串