假设我有字符串1:2:3:4:5,我想要得到它的最后一个字段(在本例中是5)。我如何使用Bash做到这一点?我试过cut,但我不知道如何用-f指定最后一个字段。
当前回答
使用Bash。
$ var1="1:2:3:4:0"
$ IFS=":"
$ set -- $var1
$ eval echo \$${#}
0
其他回答
如果你的最后一个字段是一个字符,你可以这样做:
a="1:2:3:4:5"
echo ${a: -1}
echo ${a:(-1)}
检查bash中的字符串操作。
使用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
使用read内置的解决方案:
IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"
或者,让它更通用:
echo "${fields[-1]}" # prints the last item
for x in `echo $str | tr ";" "\n"`; do echo $x; done
使用cut很难得到最后一个字段,但是这里有一些在awk和perl中的解决方案
echo 1:2:3:4:5 | awk -F: '{print $NF}'
echo 1:2:3:4:5 | perl -F: -wane 'print $F[-1]'