简体   繁体   English

使用AWK打印匹配的图案

[英]Print matched pattern with AWK

For example i have this data: 例如,我有这样的数据:

/home/test/dat1.txt
/home/test/dat2.txt
/home/test/test1/dat3.txt
/home/test/test2/dat4.txt
/home/test/test3/test4/dat5.txt

I need to print only the name and extension, that output should be: 我只需要打印名称和扩展名,输出应该是:

dat1.txt
dat2.txt
dat3.txt
dat4.txt
dat5.txt

I need to use the awk command... anyone can help? 我需要使用awk命令......任何人都可以帮忙吗?

I use this regular expression: '/\\/*\\.txt/{print ???} 我用这个正则表达式: '/\\/*\\.txt/{print ???}

If you are going to use awk , you do not need a regex for this purpose. 如果您打算使用awk ,则不需要为此目的使用正则表达式。 You can just tell awk to print the last field, using a field separator of / . 您可以使用/的字段分隔符告诉awk打印最后一个字段。

awk -F'/' '{print $NF}' Input.txt

As hd1's comment already noted, NF is the number of fields on the current input record (in this case line). 正如hd1的评论已经指出的那样, NF是当前输入记录中的字段数(在本例中为行)。 Since awk starts indexing fields at $1 , $NF gives you the last field. 由于awk开始将字段索引为$1 ,因此$NF为您提供最后一个字段。

You could use this short awk 你可以使用这个简短的awk

awk -F/ '$0=$NF' Input.txt

If you need empty line use 如果你需要空行使用

awk -F/ '{$0=$NF}1' Input.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM