简体   繁体   中英

how to print tail of path filename using awk

I've searched it with no success.

I have a file with 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

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.


Thors version

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:

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

awk solutions are already provided by @Jotne and @bashophil

Here are some other variations (just for fun)


Using sed

sed 's:.*/::' file

Using grep

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

Using cut - added by @Thor

rev file | cut -d/ -f1 | rev

Using basename - suggested by @fedorqui and @EdMorton

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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