简体   繁体   English

如何比较一个文件的linux中的记录并打印最新的

[英]How to compare the records in linux of a file and print the latest

I have the below file which has 4 columns, pipe separated.我有以下文件,它有 4 列,pipe 分开。

09252|20|30|20200426|
09252|20|10|20200406|
09252|30|10|20200427|
09252|10|20|20200327|
12112|10|20|20200530|
04442|20|10|20200612|
52552|20|10|20200614|
04442|10|20|20200530|
52552|10|20|20200530|
12112|20|10|20200613|

I have sorted the file as below using sort command.我使用 sort 命令对文件进行了如下排序。

sort input.unl排序输入.unl

04442|10|20|20200530|                                                                                                       
04442|20|10|20200612|                                                                                                       
09252|10|20|20200327|
09252|20|10|20200406|
09252|20|30|20200426|
09252|30|10|20200427|
12112|10|20|20200530|
12112|20|10|20200613|
52552|10|20|20200530|
52552|20|10|20200614|

I want to print the line into another file which has the latest date(column 4) for every entry in column 1. For example, 09252 has 4 entries in file, output file should only contain 09252|30|10|20200427|我想将该行打印到另一个文件中,该文件具有第 1 列中每个条目的最新日期(第 4 列)。例如,09252 在文件中有 4 个条目,output 文件应该只包含 09252|30|10|20200427| because this record has the latest date among 4 entries of 09252.因为这条记录在 09252 的 4 个条目中具有最新的日期。

My expected output is as below我预期的 output 如下

04442|20|10|20200612|
09252|30|10|20200427|
12112|20|10|20200613|
52552|20|10|20200614|

Looking forward to your help,期待您的帮助,

First, sort reverse by date.首先,按日期反向排序。 Then, sort and unique by the first column, keeping the order stable, so that only the last line from the previous sort, ie the max date, is kept for each id.然后,按第一列排序和唯一,保持顺序稳定,这样每个id只保留前一次排序的最后一行,即最大日期。

sort -t'|' -rk4,4 file | sort -t'|' -su -k1,1
  • -t tells sort what the delimiter is. -t告诉 sort 分隔符是什么。 We need single quotes as bare |我们需要单引号作为裸 | is a pipeline control operator.是管道控制操作员。
  • -k4,4 uses the 4 th column for sorting, ie the date -k4,4使用4 列进行排序,即日期
  • -r means sort backwards, ie the latest date will go first -r表示向后排序,即最晚日期将 go 在前
  • -k1,1 means sort by the 1 st column, ie the id -k1,1表示按1 列排序,即 id
  • -u means "unique", ie only the first occurrence of each id will be printed -u表示“唯一”,即只打印每个 id 的第一次出现
  • -s means "stable", it means sort won't shuffle the dates for the same id -s表示“稳定”,这意味着 sort 不会对相同 id 的日期进行洗牌

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM