linux - 如何使用'cut'找到最后一个字段
不使用sed或awk,仅使用cut,如果字段数未知或每行更改,如何获取最后一个字段?
noobcoder asked 2019-03-15T12:47:58Z
11个解决方案
450 votes
你可以尝试这样的事情:
echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
说明
maps.google.com的反向将是com
com使用点作为分隔符并选择第一个字段,即moc
最后,我们再次反转(感谢提醒,@ tom)获得com
zedfoxus answered 2019-03-15T12:48:42Z
95 votes
使用参数扩展。 这比任何类型的外部命令,包括cut(或grep)更有效。
data=foo,bar,baz,qux
last=${data##*,}
有关bash中本机字符串操作的介绍,请参阅BashFAQ#100。
Charles Duffy answered 2019-03-15T12:49:16Z
65 votes
不可能只使用cut.这是使用grep的方法:
grep -o '[^,]*$'
替换其他分隔符的逗号。
tom answered 2019-03-15T12:49:58Z
14 votes
没有awk?...但是用awk这么简单:
echo 'maps.google.com' | awk -F. '{print $NF}'
AWK是一种更强大的工具,可放在口袋里。-F如果是字段分隔符NF是字段数(也代表最后一个的索引)
Amir Mehler answered 2019-03-15T12:50:36Z
12 votes
有多种方式。 你也可以使用它。
echo "Your string here"| tr ' ' '\n' | tail -n1
> here
显然,tr命令的空格输入应该用你需要的分隔符替换。
rjni answered 2019-03-15T12:51:21Z
5 votes
这是唯一可以使用除切割之外的解决方案:
echo“s.t.r.i.n.g。”| 切-d'。'-f2- [repeat_following_part_forever_or_until_out_of_memory:] | 切-d'。'-f2-
使用这种解决方案,字段的数量确实是未知的,并且不时变化。 但是,由于行长度不得超过LINE_MAX字符或字段(包括换行符),因此任意数量的字段都不能成为此解决方案的真实条件。
是的,这是一个非常愚蠢的解决方案,但是我认为唯一符合标准的解决方案。
A friend answered 2019-03-15T12:52:22Z
1 votes
以下实现了朋友的建议
#!/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
user2166700 answered 2019-03-15T12:52:54Z
0 votes
如果您有一个名为filelist.txt的文件,它是一个列表路径,如下所示:C:/dir1/dir2/file1.hC:/dir1/dir2/dir3/file2.h
然后你可以这样做:rev filelist.txt | cut -d“/” - f1 |转
aperson1961 answered 2019-03-15T12:53:44Z
0 votes
我意识到如果我们只确保存在一个尾随分隔符,它就可以工作。 所以在我的情况下,我有逗号和空格分隔符。 我在最后加了一个空格;$ ans="a, b"
$ ans+=" "; echo ${ans} | tr ',' ' ' | tr -s ' ' | cut -d' ' -f2
b
AnneTheAgile answered 2019-03-15T12:54:17Z
0 votes
如果您的输入字符串不包含正斜杠,那么您可以使用|和子shell:
$ basename "$(echo 'maps.google.com' | tr '.' '/')"
这不使用|或awk,但它也不使用cut,所以我不太确定它是否有资格作为其措辞的问题的答案。
如果处理可以包含正斜杠的输入字符串,则这不起作用。 这种情况的解决方法是将正斜杠替换为您知道不属于有效输入字符串的其他字符。 例如,管道(|)字符也不允许在文件名中,因此这将起作用:
$ basename "$(echo 'maps.google.com/some/url/things' | tr '/' '|' | tr '.' '/')" | tr '|' '/'
jstine answered 2019-03-15T12:55:05Z
-1 votes
你可以用bash shell编写一个小程序。
你可以参考我的bash shell [https://www.huuphan.com/2018/06/split-string-in-shell-and-get-last-field.html]
我希望这对你有所帮助!
Phan Văn Hữu answered 2019-03-15T12:55:54Z