不使用sed或awk,只cut,当字段的数量未知或随每一行变化时,我如何得到最后一个字段?
当前回答
使用perl的替代方法是:
perl -pe 's/(.*) (.*)$/$2/' file
在哪里您可以改变\t为任何分隔符的文件是
其他回答
下面实现一个朋友的建议
#!/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
如果你有一个名为fillist .txt的文件,它是一个列表路径,如下所示: c: / dir1 dir2 / file1.h c: / dir1 dir2 / dir3 / file2.h
然后你可以这样做: Rev fillist .txt | cut -d"/" -f1 | Rev
在处理表格数据时最好使用awk。你不需要听从命令。如果awk可以实现,为什么不使用它呢?我建议您不要浪费宝贵的时间,只需使用少量命令就可以完成工作。
例子:
# $NF refers to the last column in awk
ll | awk '{print $NF}'
为这个老问题添加一个方法只是为了好玩:
$ 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。 我想,还有回声。
选择1
choose支持负索引(语法类似于Python的切片)。