如何使用awk顺序读取行

时间:2016-03-17 11:26:47

标签: awk

我的文件包含以下数据:

Line1 2016-03-16 01:12:26 17.70500 83.26889 11.90
Line2 2016-03-16 01:22:36 17.70500 83.26889 11.90
Line3 2016-03-16 01:42:25 17.70500 83.26889 11.90
Line4 2016-03-16 01:42:36 17.70500 83.26889 11.90
Line5 2016-03-16 02:12:25 17.70500 83.26889 11.90
Line6 2016-03-16 02:12:35 17.70500 83.26889 11.90

我需要一次比较行:

Line1 2016-03-16 01:12:26 17.70500 83.26889 11.90
Line2 2016-03-16 01:22:36 17.70500 83.26889 11.90

Line2 2016-03-16 01:12:26 17.70500 83.26889 11.90
Line3 2016-03-16 01:22:36 17.70500 83.26889 11.90

Line3 2016-03-16 01:12:26 17.70500 83.26889 11.90
Line4 2016-03-16 01:22:36 17.70500 83.26889 11.90

Line4 2016-03-16 01:12:26 17.70500 83.26889 11.90
Line5 2016-03-16 01:22:36 17.70500 83.26889 11.90

1 个答案:

答案 0 :(得分:2)

当然,Awk已经按顺序读取了行,而不需要你做任何额外的努力。对于要比较当前行和上一行中的信息的此类问题,您可以使用以下模板:

$ cat pcl.awk
NR == 1 { prev_line = $0 }

NR > 1 {
    print "Previous: " prev_line
    print "Current: " $0
    print "(Comparison logic here)"
    print ""
    prev_line = $0;
}

$ awk -f pcl.awk pcl.txt
Previous: Line1 2016-03-16 01:12:26 17.70500 83.26889 11.90
Current: Line2 2016-03-16 01:22:36 17.70500 83.26889 11.90
(Comparison logic here)

Previous: Line2 2016-03-16 01:22:36 17.70500 83.26889 11.90
Current: Line3 2016-03-16 01:42:25 17.70500 83.26889 11.90
(Comparison logic here)

Previous: Line3 2016-03-16 01:42:25 17.70500 83.26889 11.90
Current: Line4 2016-03-16 01:42:36 17.70500 83.26889 11.90
(Comparison logic here)

Previous: Line4 2016-03-16 01:42:36 17.70500 83.26889 11.90
Current: Line5 2016-03-16 02:12:25 17.70500 83.26889 11.90
(Comparison logic here)

Previous: Line5 2016-03-16 02:12:25 17.70500 83.26889 11.90
Current: Line6 2016-03-16 02:12:35 17.70500 83.26889 11.90
(Comparison logic here)

根据当前问题的具体情况,您可能希望保存一个或多个特定字段$3,例如,而不是整行($0),但是一般形式解决方案或多或少相同。