Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all lines matching the first field of last line

I've been trying to do this for the last two days. I read a lot of tutorials and I learned a lot of new things but so far I couldn't manage to achieve what I'm trying to do. Let's say this is the command line output:

Johnny123   US  224
Johnny123   US  145
Johnny123   US  555
Johnny123   US  344
Robert  UK  4322
Robert  UK  52
Lucas   FR  344
Lucas   FR  222
Lucas   FR  8945

I want to print the lines which match 'the first field (Lucas) of last line'.

So, I want to print out:

Lucas   FR  344
Lucas   FR  222
Lucas   FR  8945

Notes:

  • What I'm trying to print have a different line count each time so I can't do something like returning the last 3 lines only.
  • The first field doesn't have a specific pattern that I can use to print.
like image 747
Sameh Avatar asked Dec 11 '25 15:12

Sameh


1 Answers

Here is another way using tac and awk:

tac file | awk 'NR==1{last=$1}$1==last' | tac
Lucas   FR  344
Lucas   FR  222
Lucas   FR  8945

The last tac is only needed if the order is important.

like image 113
jaypal singh Avatar answered Dec 14 '25 04:12

jaypal singh