使用awk substr获取最后一个字段 [英] Get last field using awk substr
问题描述
在给定文件绝对路径的情况下,我试图使用awk
来获取文件名.
例如,当给定输入路径/home/parent/child/filename
时,我想获取filename
我已经尝试过:
I am trying to use awk
to get the name of a file given the absolute path to the file.
For example, when given the input path /home/parent/child/filename
I would like to get filename
I have tried:
awk -F "/" '{print $5}' input
效果很好.
但是,我正在对$5
进行硬编码,如果我的输入具有以下结构,这将是不正确的:
which works perfectly.
However, I am hard coding $5
which would be incorrect if my input has the following structure:
/home/parent/child1/child2/filename
因此,通用解决方案始终需要使用 last 字段(将是文件名).
So a generic solution requires always taking the last field (which will be the filename).
使用awk substr函数有一种简单的方法吗?
Is there a simple way to do this with the awk substr function?
推荐答案
使用以下事实:awk
根据您可以定义的字段分隔符拆分字段中的行.因此,将字段分隔符定义为/
可以说:
Use the fact that awk
splits the lines in fields based on a field separator, that you can define. Hence, defining the field separator to /
you can say:
awk -F "/" '{print $NF}' input
如NF
表示当前记录的字段数,打印$NF
表示打印最后一个字段.
as NF
refers to the number of fields of the current record, printing $NF
means printing the last one.
因此,给定这样的文件:
So given a file like this:
/home/parent/child1/child2/child3/filename
/home/parent/child1/child2/filename
/home/parent/child1/filename
这将是输出:
$ awk -F"/" '{print $NF}' file
filename
filename
filename
这篇关于使用awk substr获取最后一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!