使用 AWK 比较多个文件中的字段时的条件匹配

Conditional match when comparing fields in multiple files using AWK

我想知道 how/whether 在 AIX 6.x 平台上的 AWK 中比较来自不同文件的多个字段时是否可以包含一些条件。以下是我正在尝试做的事情:

Employee.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|basketballCeline|Wood|Atlanta|
6|tennis|Jody|Ford|Chicago|

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

我想在打印匹配记录之前检查员工状态是否为 Active(无 X)以及汽车可用性(Y)是否相同。这可行吗?

非常感谢, 乔治

使用您显示的示例,请尝试以下 awk 代码。

awk '
BEGIN{ FS=OFS="|" }
FNR==NR{
  arr[]=$NF
  arr1[]=[=10=]
  next
}
arr[]!="X" && $NF=="Y"{
  print arr1[] > ("match.txt")
  arr2[]
}
END{
  for(i in arr1){
    if(!(i in arr2)){
      print arr1[i] > ("no_match.txt")
    }
  }
}
' Employee.txt car.txt

说明:为以上代码添加详细说明。

awk '                                      ##Starting awk program from here.
BEGIN{ FS=OFS="|" }                        ##Setting FS and OFS to | in BEGIN section.
FNR==NR{                                   ##Checking condition FNR==NR which will be TRUE when Employee.txt is being read.
  arr[]=$NF                              ##Creating array arr with index of  and value of last field.
  arr1[]=[=11=]                              ##Creating array arr1 with index of  and value of current line.
  next                                     ##next will skip all further statements from here.
}
arr[]!="X" && $NF=="Y"{                  ##Checking condition if arr array with index of 3rd column value is not X and last field is Y then do following.
  print arr1[] > ("match.txt")           ##Printing respective entry from Employee.txt into match.txt file here.
  arr2[]                                 ##Creating an entry in arr2 with index of  here.
}
END{                                       ##Starting END block of this awk program from here.
  for(i in arr1){                          ##Traversing through arr1 here.
    if(!(i in arr2)){                      ##Checking if i(current item index) is NOT present in arr2 then do following.
      print arr1[i] > ("no_match.txt")     ##Printing respective value to no_match.txt file.
    }
  }
}
' Employee.txt car.txt                     ##Mentioning Input_file names here.

这个怎么样:

awk -F'|' 'FNR==NR { empcar[]; next }  in empcar &&  != "X"' cars emps

输出:

2|Barry|Jones|Seatle|
6|Jody|Ford|Chicago|

以下是检查两个文件中其他条件的方法:

awk -F"|" '
NR==FNR {
   if ($NF == "Y")
      empcar[$(NF-1)]
   next
}
{
   print > ($NF != "X" &&  in empcar ? "match.txt" : "no_match.txt")
}' Car.txt Employee.txt