2014-02-07 41 views
1

我需要comapre f1.txt和f2.txt兩個文件並獲得匹配和非匹配,對於這種情況 我期待檢查第二個字段f1.txt的第一個字段與f2.txt的第一個字段相匹配,如果是 則打印f1.txt的整行並打印f2.txt的第一個字段和f2.txt的第二個字段的和。並且在f1.txt中找不到匹配「NotFound」的匹配項。awk查找2個文件,打印匹配和Sencond字段總和:

f1.txt

aa,10,cc,Jan-13 
bb,20,cc,Feb-13 
dd,50,cc,Mar-13 

f2.txt

10,1500,ss 
20,500,gg 
10,2000,kk 
10,15000,yy 
20,500,zz, 
35,250,tt 

Output.txt的

aa,10,cc,Jan-13,10,18500 
bb,20,cc,Feb-13,20,1000 
dd,50,cc,Mar-13,NotFound,NotFound 

回答

3

awk應該做

awk -F, 'FNR==NR {a[$1]+=$2;next} {if ($2 in a) print $0,$2,a[$2]; else print $0,"NotFound","NotFound"}' OFS=, f2.txt f1.txt 
aa,10,cc,Jan-13,10,18500 
bb,20,cc,Feb-13,20,1000 
dd,50,cc,Mar-13,NotFound,NotFound 

它是如何工作:

awk -F, '          #Set Field separator to , 
    FNR==NR {a[$1]+=$2;next}     #Read data from file f2.txt using field #1 as index and sum field #2 in to array a 
    {if ($2 in a)        #Test if field #2 in f1.txt is found in a 
     print $0,$2,a[$2]      #If found, print line of f1.txt with sum and index from array 
     else print $0,"NotFound","NotFound"  #If not found print line of f1.txt with NotFound 
    } 
    ' OFS=, f2.txt f1.txt      #Set Output field separator to , and read files 

稍短的版本:

awk -F, 'FNR==NR {a[$1]+=$2;next} {print $0 ","($2 in a?$2","a[$2]:"NotFound,NotFound")}' f2.txt f1.txt 
+0

非常感謝Jotne,它工作正常.. – SVR

相關問題