unix - 使用 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.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
## 包含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`
解决方案
使用您显示的示例,请尝试以下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[$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
推荐阅读
- python - 被阻止时如何在Scrapy中暂停蜘蛛
- reactjs - babel 7 不允许在装饰器和类之间使用 export 关键字。请改用`export @dec class`
- networking - 计算网络地址
- python - 如何从向导 Odoo 11 编写另一个字段
- database - Laravel 和 Websockets 中的实时数据库
- angular - 在 Build 目录中找不到 Angular 6 延迟加载模块以及另外 2 个应用程序
- dynamics-crm - 在动态 crm 集线器中编辑“顶部栏”
- python - sympy 解决方法或乳胶解析器有问题吗?
- db2 - DB2 REORG 命令无法启动
- deep-learning - Runnig DeepPavlov 命名实体识别