不使用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
在处理表格数据时最好使用awk。你不需要听从命令。如果awk可以实现,为什么不使用它呢?我建议您不要浪费宝贵的时间,只需使用少量命令就可以完成工作。
例子:
# $NF refers to the last column in awk
ll | awk '{print $NF}'
使用perl的替代方法是:
perl -pe 's/(.*) (.*)$/$2/' file
在哪里您可以改变\t为任何分隔符的文件是
你可以尝试这样做:
echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
解释
Rev将maps.google.com颠倒为moc.elgoog.spam Cut使用点(即“。”)作为分隔符,并选择第一个字段,即moc 最后,我们再次反向得到com
这是不可能只使用切割。下面是使用grep的方法:
grep -o '[^,]*$'
用逗号替换其他分隔符。
解释:
-o (--only-matching) only outputs the part of the input that matches the pattern (the default is to print the entire line if it contains a match). [^,] is a character class that matches any character other than a comma. * matches the preceding pattern zero or more time, so [^,]* matches zero or more non‑comma characters. $ matches the end of the string. Putting this together, the pattern matches zero or more non-comma characters at the end of the string. When there are multiple possible matches, grep prefers the one that starts earliest. So the entire last field will be matched.
完整的例子:
如果我们有一个叫data。csv的文件包含
one,two,three
foo,bar
然后输出grep -o '[^,]*$' < data.csv
three
bar