[英]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'. 我想打印与“最后一行的第一个字段(Lucas)”匹配的行。
So, I want to print out: 所以,我想打印出来:
Lucas FR 344
Lucas FR 222
Lucas FR 8945
Notes: 笔记:
Here is another way using tac
and awk
: 这是使用tac
和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. 只有在订单很重要时才需要最后一个tac
。
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): 这可能适合你(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. 在文件末尾打印剩下的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.