首页 > 解决方案 > 使用 Unix 比较两个管道分隔文件

问题描述

File_1.txt

emp_id|emp_name|emp_dob
111|Alex|08/29/1994
222|John|05/12/1997
333|Sam|08/24/1987

File_2.txt

emp_id|emp_dob|emp_name
111|08/29/1994|Alex
444|05/12/2000|John
222|05/12/1997|Brad

需要比较File_1.txt和使用 header( )File_2.txt中提到的列,可用于连接条件head -1 File_1.txtemp_id

经过比较,应该会生成以下文件

Mismatch.txt ## 包含不匹配的值emp_id

File_name|column_name|emp_id|File_1_value|File_2_value
File 1|emp_name|222|John|Brad

Missing_Rows.txt ## 包含emp_id文件 1 或文件 2 中缺少的 s

File_name|emp_id
File 1|444
File 2|333

我可以使用 join 命令加入 2 个文件,但无法找到 Missing 和 Mismatch 行的详细信息。

join -j1 -t'|' -o1.1,1.2,1.3,2.1,2.2,2.3 <(cat  File_1.txt|awk -F'|' '{print $0}'|sort  -t '|' -k1,1)<( cat  File_2.txt|awk -F'|' '{print $0}'|sort -t '|' -k1,1) > joinfile.txt`

标签: unixscriptingsh

解决方案


使用您显示的示例,请尝试以下awk代码。它将根据要求创建 2 个名为Mismatch.txtMissing_Rows.txt的输出文件。

awk '
BEGIN{
  FS=OFS="|"
  print "File_name|column_name|emp_id|File_1_value|File_2_value" > "Mismatch.txt"
  print "File_name|emp_id" > "Missing_Rows.txt"
}
FNR==NR{
  empId1[$1]=FILENAME OFS $0
  empId2[$1]=$2
  empVal[$1,$2]=$0
  next
}
{ empId3[$1] }
!($1 in empId1){
  print (FILENAME,$1) > "Missing_Rows.txt"
  next
}
($1 in empId1) && !(($1,$3) in empVal){
  print (FILENAME,empId2[$1],$NF) > "Mismatch.txt"
}
END{
  for(i in empId1){
    if(!(i in empId3)){
      split(empId1[i],arr,"|")
      print (arr[1],arr[2]) > "Missing_Rows.txt"
    }
  }
}
' file1.txt file2.txt

推荐阅读