不使用sed或awk,只cut,当字段的数量未知或随每一行变化时,我如何得到最后一个字段?
当前回答
使用参数展开。这比包括cut(或grep)在内的任何外部命令都要有效得多。
data=foo,bar,baz,qux
last=${data##*,}
参见BashFAQ #100,了解bash中本地字符串操作的介绍。
其他回答
下面实现一个朋友的建议
#!/bin/bash
rcut(){
nu="$( echo $1 | cut -d"$DELIM" -f 2- )"
if [ "$nu" != "$1" ]
then
rcut "$nu"
else
echo "$nu"
fi
}
$ export DELIM=.
$ rcut a.b.c.d
d
你可以尝试这样做:
echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
解释
Rev将maps.google.com颠倒为moc.elgoog.spam Cut使用点(即“。”)作为分隔符,并选择第一个字段,即moc 最后,我们再次反向得到com
我意识到,如果我们只是确保后面的分隔符存在,它就可以工作。在我的例子中,我有逗号和空格分隔符。我在结尾加了一个空格;
$ ans="a, b"
$ ans+=" "; echo ${ans} | tr ',' ' ' | tr -s ' ' | cut -d' ' -f2
b
使用perl的替代方法是:
perl -pe 's/(.*) (.*)$/$2/' file
在哪里您可以改变\t为任何分隔符的文件是
为这个老问题添加一个方法只是为了好玩:
$ cat input.file # file containing input that needs to be processed
a;b;c;d;e
1;2;3;4;5
no delimiter here
124;adsf;15454
foo;bar;is;null;info
$ cat tmp.sh # showing off the script to do the job
#!/bin/bash
delim=';'
while read -r line; do
while [[ "$line" =~ "$delim" ]]; do
line=$(cut -d"$delim" -f 2- <<<"$line")
done
echo "$line"
done < input.file
$ ./tmp.sh # output of above script/processed input file
e
5
no delimiter here
15454
info
除了bash,只使用cut。 我想,还有回声。