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


当前回答

for x in `echo $str | tr ";" "\n"`; do echo $x; done

其他回答

对于那些熟悉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库。

你可以使用字符串操作符:

$ foo=1:2:3:4:5
$ echo ${foo##*:}
5

这将从前面到':'贪婪地修剪所有内容。

${foo  <-- from variable foo
  ##   <-- greedy front trim
  *    <-- matches anything
  :    <-- until the last ':'
 }
for x in `echo $str | tr ";" "\n"`; do echo $x; done

使用read内置的解决方案:

IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"

或者,让它更通用:

echo "${fields[-1]}" # prints the last item
$ echo "a b c d e" | tr ' ' '\n' | tail -1
e

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