使用 Unix 比较两个管道分隔文件
Compare two pipe delimited files using 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
需要使用header(head -1 File_1.txt
)中提到的列来比较File_1.txt
和File_2.txt
,emp_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
## 包含文件 1 或文件 2
中缺少的 emp_id
File_name|emp_id
File 1|444
File 2|333
我可以使用连接命令连接这 2 个文件,但无法找到缺失和不匹配行的详细信息。
join -j1 -t'|' -o1.1,1.2,1.3,2.1,2.2,2.3 <(cat File_1.txt|awk -F'|' '{print [=14=]}'|sort -t '|' -k1,1)<( cat File_2.txt|awk -F'|' '{print [=14=]}'|sort -t '|' -k1,1) > joinfile.txt`
使用您显示的示例,请尝试以下 awk
代码。它将根据要求创建 2 个名为 Mismatch.txt
和 Missing_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[]=FILENAME OFS [=10=]
empId2[]=
empVal[,]=[=10=]
next
}
{ empId3[] }
!( in empId1){
print (FILENAME,) > "Missing_Rows.txt"
next
}
( in empId1) && !((,) in empVal){
print (FILENAME,empId2[],$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
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
需要使用header(head -1 File_1.txt
)中提到的列来比较File_1.txt
和File_2.txt
,emp_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
## 包含文件 1 或文件 2
emp_id
File_name|emp_id
File 1|444
File 2|333
我可以使用连接命令连接这 2 个文件,但无法找到缺失和不匹配行的详细信息。
join -j1 -t'|' -o1.1,1.2,1.3,2.1,2.2,2.3 <(cat File_1.txt|awk -F'|' '{print [=14=]}'|sort -t '|' -k1,1)<( cat File_2.txt|awk -F'|' '{print [=14=]}'|sort -t '|' -k1,1) > joinfile.txt`
使用您显示的示例,请尝试以下 awk
代码。它将根据要求创建 2 个名为 Mismatch.txt
和 Missing_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[]=FILENAME OFS [=10=]
empId2[]=
empVal[,]=[=10=]
next
}
{ empId3[] }
!( in empId1){
print (FILENAME,) > "Missing_Rows.txt"
next
}
( in empId1) && !((,) in empVal){
print (FILENAME,empId2[],$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