我想了解如何/是否可以在比較 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[$3]
next
}
{
print > ($1 in empcar ? "match.txt" : "no_match.txt")
}' Car.txt Employee.txt
我喜歡在列印匹配的記錄之前檢查員工狀態是否為活動(無 X)和汽車可用性(Y)是否相同。這是可行的嗎?
非常感謝,喬治
uj5u.com熱心網友回復:
以下是檢查兩個檔案中其他條件的方法:
awk -F"|" '
NR==FNR {
if ($NF == "Y")
empcar[$(NF-1)]
next
}
{
print > ($NF != "X" && $1 in empcar ? "match.txt" : "no_match.txt")
}' Car.txt Employee.txt
uj5u.com熱心網友回復:
這個怎么樣:
awk -F'|' 'FNR==NR { empcar[$3]; next } $1 in empcar && $5 != "X"' cars emps
輸出:
2|Barry|Jones|Seatle|
6|Jody|Ford|Chicago|
uj5u.com熱心網友回復:
使用您顯示的示例,請嘗試以下awk代碼。
awk '
BEGIN{ FS=OFS="|" }
FNR==NR{
arr[$1]=$NF
arr1[$1]=$0
next
}
arr[$3]!="X" && $NF=="Y"{
print arr1[$3] > ("match.txt")
arr2[$3]
}
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[$1]=$NF ##Creating array arr with index of $1 and value of last field.
arr1[$1]=$0 ##Creating array arr1 with index of $1 and value of current line.
next ##next will skip all further statements from here.
}
arr[$3]!="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[$3] > ("match.txt") ##Printing respective entry from Employee.txt into match.txt file here.
arr2[$3] ##Creating an entry in arr2 with index of $3 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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375008.html
上一篇:Python子行程沒有將大括號作為引數傳遞?或者雙引號的問題
下一篇:無法構建陣列并在AWK中列印出來
