简体   繁体   English

如何使用awk打印路径文件名的尾部

[英]how to print tail of path filename using awk

I've searched it with no success. 我搜索它没有成功。

I have a file with pathes. 我有一个带有pathes的文件。 I want to print the tail of a all pathes. 我想要打印所有路径的尾部。 for example (for every line in file): 例如(对于文件中的每一行):

/homes/work/abc.txt
--> abc.txt

Does anyone know how to do it? 有谁知道怎么做?

Thanks 谢谢

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

will give output of: 将给出的输出:

abc1.txt
abc2.txt
abc3.txt

for: 对于:

$>cat input.txt
text path/to/file/abc1.txt
path/to/file/abc2.txt
path/to/file/abc3.txt

How about this awk 这个awk怎么样?

echo "/homes/work/abc.txt" | awk '{sub(/.*\//,x)}1'
abc.txt

Since .* is greedy, it will continue until last / 由于.*是贪婪的,它会一直持续到最后/
So here we remove all until last / with x , and since x is empty, gives nothing. 所以在这里我们删除所有直到最后/x ,因为x是空的,什么都不给。


Thors version Thors版本

echo "/homes/work/abc.txt" | awk -F/ '$0=$NF'
abc.txt

NB this will fail for /homes/work/0 or 0,0 etc so better use: 注意这对于/homes/work/00,0等都会失败,所以更好用:

echo "/homes/work/abc.txt" | awk -F/ '{$0=$NF}1'

awk solutions are already provided by @Jotne and @bashophil awk解决方案已由@Jotne@bashophil提供

Here are some other variations (just for fun) 这里有一些其他的变化(只是为了好玩)


Using sed 使用sed

sed 's:.*/::' file

Using grep 使用grep

grep -oP '(.*/)?\K.*' file

Using cut - added by @Thor 使用cut - 由@Thor添加

rev file | cut -d/ -f1 | rev

Using basename - suggested by @fedorqui and @EdMorton 使用basename - 由@fedorqui@EdMorton建议

while IFS= read -r line; do 
  basename "$line" 
done < file

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

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