简体   繁体   English

如何打印与最后一行的第一个字段匹配的所有行

[英]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: 笔记:

  • 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. 我正在尝试打印的内容每次都有不同的行数,所以我不能做只返回最后3行的事情。
  • The first field doesn't have a specific pattern that I can use to print. 第一个字段没有我可以用来打印的特定模式。

Here is another way using tac and awk : 这是使用tacawk另一种方式:

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.

相关问题 用于合并具有匹配第一个字段的行的命令行,50 GB 输入 - Command line to merge lines with matching first field, 50 GB input 如何将第一行的第一个字段复制到后续行中? - How do I copy the first field of the first line into succeeding lines? 在Vim之后如何删除与模式和行匹配的所有行? - How to delete all lines matching a pattern and a line after in Vim? 命令行以匹配具有匹配的第一字段(sed,awk等)的行 - Command line to match lines with matching first field (sed, awk, etc.) 如何删除字符串第一次出现之前和最后一次出现之后的所有行? - How to delete all lines before the first and after the last occurrence of a string? sed:需要删除除了匹配字符串的第一行或最后一行之外的所有行 - sed : Need to remove all lines except first or last line that matches a string 如果第二行包含与第一行相同的匹配,如何打印2行? - How can I print 2 lines if the second line contains the same match as the first line? 如何以str格式返回(不打印)所有匹配的行? 字符串是一个长字符串,用\\ t和\\ n分隔 - How to return (not print) all matching lines in str format? string is a long string separated by \t's & \n's 匹配第一个字段的打印行(bash) - print line that matches first field (bash) 匹配包含的第一行之后的所有行 - Match all lines after the first line that contains
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM