在python或Shell中逐行比较字段数据

时间:2016-06-22 14:54:20

标签: python shell unix ksh

我的输入文件包含以下数据:

Mode|Date|Count|timestamp|status
HR|06/08/2016|3000|Thu Jun 09 2016|Complete
HR|06/08/2016|3010|Thu Jun 09 2016|Complete
HR|06/08/2016|2000|Thu Jun 09 2016|Complete
HR|06/08/2016|2000|Fri Jun 09 2016|Complete
HR|06/08/2016|1000|Thu Jun 09 2016|Complete
HR|06/08/2016|1500|Thu Jun 09 2016|Failure
....

现在我试图比较每两行以找出哪个字段有数据不匹配。我用很多方法尝试使用python脚本。但没有发现任何运气。我的输出应该如下

Count Mismatch:
HR|06/08/2016|3000|Thu Jun 09 2016|Complete
HR|06/08/2016|3010|Thu Jun 09 2016|Complete
timestamp Mismatch:
HR|06/08/2016|2000|Thu Jun 09 2016|Complete
HR|06/08/2016|2000|Fri Jun 09 2016|Complete
Count and Status Mismatch:
HR|06/08/2016|1000|Thu Jun 09 2016|Complete
HR|06/08/2016|1500|Thu Jun 09 2016|Failure
....

有人可以帮我吗?在此先感谢

1 个答案:

答案 0 :(得分:1)

您可以使用awk:

awk 'BEGIN{
   FS="|"
}
NR==1 {
   split($0, h, /\|/)
   next
}
NR%2==0 {
   pr=$0
   split($0, a, /\|/)
   next
}
{
   s = ""
   for(i=1; i<=NF; i++)
      if ($i != a[i])
         s = sprintf("%s%s", s, (!s? "" : " and ") h[i])
   print s, "Mismatch:" ORS pr ORS $0
}' file

Count Mismatch:
HR|06/08/2016|3000|Thu Jun 09 2016|Complete
HR|06/08/2016|3010|Thu Jun 09 2016|Complete
timestamp Mismatch:
HR|06/08/2016|2000|Thu Jun 09 2016|Complete
HR|06/08/2016|2000|Fri Jun 09 2016|Complete
Count and status Mismatch:
HR|06/08/2016|1000|Thu Jun 09 2016|Complete
HR|06/08/2016|1500|Thu Jun 09 2016|Failur