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


当前回答

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

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

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

然后,用xargs修整

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

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

其他回答

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

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

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

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

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

使用Bash。

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

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

$ foo=1:2:3:4:5
$ echo ${foo} | sed "s/.*://"
5

使用read内置的解决方案:

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

或者,让它更通用:

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