5

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

jkshah
  • 11,387
  • 6
  • 35
  • 45
Noam Mizrachi
  • 512
  • 2
  • 6
  • 15

3 Answers3

7
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
EverythingRightPlace
  • 1,197
  • 12
  • 33
5

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'
Jotne
  • 40,548
  • 12
  • 51
  • 55
4

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
jkshah
  • 11,387
  • 6
  • 35
  • 45
  • @fedorqui Thanks for your suggestion! Added to solution. – jkshah Nov 11 '13 at 10:59
  • Note in my proposed version it won't fail if file paths have white spaces, because quoting the variable when calling `basename` avoids it. – fedorqui Nov 11 '13 at 11:01
  • @fedorqui that's cool. actually i had tried the same earlier but might have missed quotes so decided to go with `xargs` as produced results were same. Now I have removed that bad practice. This is *fun*. Thanks :) – jkshah Nov 11 '13 at 11:07
  • The loop will fail if your file names contain backslashes or can start with white space. Always us `while IFS= read -r line` unless you have a very specific reason not to. Obviously, the approach just won't work at all if the file names contain newlines but that's a whole other can of worms. – Ed Morton Nov 11 '13 at 16:25