bash - 如何在shell中拆分字符串并获取最后一个字段
假设我有字符串1:2:3:4:5,我想得到它的最后一个字段(在这种情况下为5)。 我如何使用Bash做到这一点? 我试过cut,但我不知道如何用-f指定最后一个字段。
cd1 asked 2019-02-25T17:48:20Z
14个解决方案
331 votes
您可以使用字符串运算符:
$ foo=1:2:3:4:5
$ echo ${foo##*:}
5
从the:This This This This This This This This trim trim trim trim trim trim。
${foo
##
*
:
}
Stephen answered 2019-02-25T17:48:42Z
301 votes
另一种方法是在cut之前和之后反转:
$ echo ab:cd:ef | rev | cut -d: -f1 | rev
ef
这使得很容易获得最后一个字段,或从末尾编号的任何字段范围。
a3nm answered 2019-02-25T17:49:19Z
63 votes
使用cut获取最后一个字段很困难,但这里是awk和perl中的(一组)解决方案
$ echo 1:2:3:4:5 | awk -F: '{print $NF}'
5
$ echo 1:2:3:4:5 | perl -F: -wane 'print $F[-1]'
5
William Pursell answered 2019-02-25T17:50:02Z
24 votes
假设使用相当简单(例如,没有转义分隔符),您可以使用grep:
$ echo "1:2:3:4:5" | grep -oE "[^:]+$"
5
细分 - 在行的末尾找到所有字符而不是分隔符([^:])($)。 -o仅打印匹配的部分。
Nicholas M T Elliott answered 2019-02-25T17:50:38Z
18 votes
单程:
var1="1:2:3:4:5"
var2=${var1##*:}
另一个,使用数组:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
var2=${var2[@]: -1}
另一个有阵列:
var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
count=${#var2[@]}
var2=${var2[$count-1]}
使用Bash(版本> = 3.2)正则表达式:
var1="1:2:3:4:5"
[[ $var1 =~ :([^:]*)$ ]]
var2=${BASH_REMATCH[1]}
Dennis Williamson answered 2019-02-25T17:51:34Z
8 votes
$ echo "a b c d e" | tr ' ' '\n' | tail -1
e
只需将分隔符转换为换行符,然后选择最后一个条目tail -1。
user3133260 answered 2019-02-25T17:52:02Z
5 votes
使用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
Rafael answered 2019-02-25T17:52:29Z
4 votes
如果您的最后一个字段是单个字符,则可以执行以下操作:
a="1:2:3:4:5"
echo ${a: -1}
echo ${a:(-1)}
检查bash中的字符串操作。
Ab Irato answered 2019-02-25T17:53:05Z
3 votes
这里有很多好的答案,但我仍想使用basename分享这个:
basename $(echo "a:b:c:d:e" | tr ':' '/')
但是如果你的字符串中已经有一些'/',它将会失败。如果斜杠/是您的分隔符,那么您只需(并且应该)使用basename。
这不是最佳答案,但它只是展示了如何使用bash命令创造性。
021 answered 2019-02-25T17:53:54Z
2 votes
使用Bash。
$ var1="1:2:3:4:0"
$ IFS=":"
$ set -- $var1
$ eval echo \$${#}
0
ghostdog74 answered 2019-02-25T17:54:26Z
2 votes
echo "a:b:c:d:e"|xargs -d : -n1|tail -1
首先使用xargs使用“:”分割它, - n1表示每行只有一个部分。然后,pring最后一部分。
Crytis answered 2019-02-25T17:55:04Z
1 votes
for x in `echo $str | tr ";" "\n"`; do echo $x; done
Nahid Akbar answered 2019-02-25T17:55:23Z
1 votes
对于那些熟悉Python的人来说,[https://github.com/Russell91/pythonpy]是解决这个问题的不错选择。
$ echo "a:b:c:d:e" | py -x 'x.split(":")[-1]'
来自pythonpy的帮助:-x treat each row of stdin as x。
使用该工具,可以轻松编写应用于输入的python代码。
Christoph Böddeker answered 2019-02-25T17:56:08Z
0 votes
使用read builtin的解决方案
IFS=':' read -a field <<< "1:2:3:4:5"
echo ${field[4]}
baz answered 2019-02-25T17:56:36Z