不使用sed或awk,只cut,当字段的数量未知或随每一行变化时,我如何得到最后一个字段?
当前回答
没有awk ? 但是用awk很简单:
echo 'maps.google.com' | awk -F. '{print $NF}'
AWK是一个更强大的工具,可以放在你的口袋里。 -F if用于字段分隔符 NF是字段的数量(也表示最后一个字段的索引)
其他回答
下面实现一个朋友的建议
#!/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
这是不可能只使用切割。下面是使用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
如果你的输入字符串不包含正斜杠,那么你可以使用basename和subshell:
$ basename "$(echo 'maps.google.com' | tr '.' '/')"
它不使用sed或awk,但也不使用cut,所以我不太确定它是否有资格作为问题的答案。
如果处理可能包含正斜杠的输入字符串,这就不能很好地工作。对于这种情况,一种变通方法是将正斜杠替换为其他一些您知道不是有效输入字符串的一部分的字符。例如,管道(|)字符也不允许出现在文件名中,所以这是可行的:
$ basename "$(echo 'maps.google.com/some/url/things' | tr '/' '|' | tr '.' '/')" | tr '|' '/'
使用参数展开。这比包括cut(或grep)在内的任何外部命令都要有效得多。
data=foo,bar,baz,qux
last=${data##*,}
参见BashFAQ #100,了解bash中本地字符串操作的介绍。
如果你有一个名为fillist .txt的文件,它是一个列表路径,如下所示: c: / dir1 dir2 / file1.h c: / dir1 dir2 / dir3 / file2.h
然后你可以这样做: Rev fillist .txt | cut -d"/" -f1 | Rev