簡體   English   中英

使用 AWK 在不同文件中進行多字段比較的條件匹配

[英]Conditional matching with multiple fields comparison in different files using AWK

我再次需要您的幫助,了解如何匹配 2 個單獨文件中的 2 個字段/列,包括記錄的條件匹配(Employee.txt 中的狀態 <> 'X' 和 Car.txt 中的可用性 = 'Y')。 Employee.txt($1 - 員工編號,$2 - 運動)。 Car.txt($4 - 員工編號,$2 - 運動)。 以下是我想要實現的目標:

Employee1.txt (last column is the **status**)
1|canoeing|Sam|Smith|Seatle|X
2|jogging|Barry|Jones|Seatle|
3|football|Garry|Brown|Houston|
4|jogging|George|Bla|LA|X
5|basketball|Celine|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

Car1.txt (last column is **availability**)
100|football|blue|5|Y
110|tennis|green|9|N
120|hockey|yellow|8|N
130|football|yellow|6|N
140|jogging|red|2|Y
150|canoeing|white|0|
    
awk -F"|" '
NR==FNR {
  if ($NF == "Y")
     car[$4,$2]
     next
}
{
    print > ($NF != "X" && ($1,$2) in car ? "match.txt" : "no_match.txt")
}' Car.txt Employee.txt

no_match.txt is the same as Employee.txt. Zero records in match.txt.

Desire output:
match.txt
2|jogging|Barry|Jones|Seatle|
5|basketball|Celine|Wood|Atlanta|

no_match.txt
3|football|Garry|Brown|Houston|
6|tennis|Jody|Ford|Chicago|

非常感謝,喬治

注意:根據您的要求,

5|basketball|Celine|Wood|Atlanta|

應該在 match.txt 中,因為兩個文件中的運動不同(足球與籃球

如果您想要“no_match.txt”中的status "X"條目:

$  awk -F"|" '                
NR==FNR { if ($NF == "Y") car[$4 FS $2]=1; next }
{ print > ( ($NF!="X" && ($1 FS $2) in car) ? "match.txt" : "no_match.txt") }' c.txt e.txt

結果:

kent$  head match.txt no_match.txt
==> match.txt <==
2|jogging|Barry|Jones|Seatle|

==> no_match.txt <==
1|canoeing|Sam|Smith|Seatle|X
2|jogging|Barry|Jones|Seatle|
3|football|Garry|Brown|Houston|
4|jogging|George|Bla|LA|X
5|basketball|Celine|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

如果要排除“X”條目:

kent$  awk -F"|" '                
NR==FNR { if ($NF == "Y") car[$4 FS $2]=1; next }
$NF!="X"{ print > (($1 FS $2) in car? "match.txt" : "no_match.txt") }' c.txt e.txt 

結果:

kent$  head match.txt no_match.txt
==> match.txt <==
2|jogging|Barry|Jones|Seatle|

==> no_match.txt <==
3|football|Garry|Brown|Houston|
5|basketball|Celine|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM