Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print tail of path filename using awk

Tags:

linux

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

like image 971
Noam Mizrachi Avatar asked Nov 10 '13 14:11

Noam Mizrachi


3 Answers

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
like image 192
EverythingRightPlace Avatar answered Oct 21 '22 16:10

EverythingRightPlace


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'
like image 30
Jotne Avatar answered Oct 21 '22 16:10

Jotne


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
like image 30
jkshah Avatar answered Oct 21 '22 16:10

jkshah