简体   繁体   中英

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.

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.

awk 'NR==FNR{key=$1;next} $1==key' file file

或者如果你愿意的话

awk '{val[$1]=val[$1] $0 RS; key=$1} END{printf "%s", val[key]}' file

This might work for you (GNU sed):

sed -nr 'H;g;/^(\S+\s).*\n\1[^\n]*$/!{s/.*\n//;h};$p' file

Store lines with duplicate keys in the hold space. At change of key remove previous lines. At end-of-file print out what remains.

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