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


当前回答

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

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

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

${foo  <-- from variable foo
  ##   <-- greedy front trim
  *    <-- matches anything
  :    <-- until the last ':'
 }

其他回答

sed中的正则表达式匹配是贪婪的(总是到最后一个出现),你可以在这里使用它:

$ foo=1:2:3:4:5
$ echo ${foo} | sed "s/.*://"
5
for x in `echo $str | tr ";" "\n"`; do echo $x; done

使用Bash。

$ var1="1:2:3:4:0"
$ IFS=":"
$ set -- $var1
$ eval echo  \$${#}
0

使用read内置的解决方案:

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

或者,让它更通用:

echo "${fields[-1]}" # prints the last item

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

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

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

${foo  <-- from variable foo
  ##   <-- greedy front trim
  *    <-- matches anything
  :    <-- until the last ':'
 }