我有兩個文件。 DOMAIN.txt文件包含某些領域一個awk腳本錯誤我無法修復
facebook.com
google.com
yahoo.com
site.txt包含域下的一些網站,他們的URL數量。
music.google.com 2
image.google.com 3
music.facebook.com 8
image.facebook.com 4
map.yahoo.com 4
new.yahoo.com 7
我打算選擇這些網站,它的網址數大於其網域的平均網址數。例如,google.com的平均網址編號爲(2 + 3)/2=2.5,因此將挑選image.google.com。
我寫awk腳本是這樣的:
BEGIN {
#read all domains into memory
while(getline dom < "./domain.txt" > 0){
domain[dom]=0;
}
#count URLs number and sites number under each domain
for (dom in domain){
sitenumber=0;
close("./site.txt")
while(getline < "./site.txt" >0){
if(match($1,"."dom"$")){
domain[dom]+=$2;
sitenumber++;
printf("%s\n",$0) >> "./sitesunderdomain";
}
}
avgsitenumber = domain[dom]/sitenumber;
system("cat ./sitesunderdomain") #test output
close("./sitesunderdomain")
while(getline < "./sitesunderdomain" >0){ #loop A
print "why1" #test output
if($2>=avgsitenumber){
print "why2" #testoutput
print $0,avgsitenumber>>"./result"
}
}
system("> ./sitesunderdomain")
}#for
}
然後我跑在猛砸awk腳本,得到輸出:
music.facebook.com 8
image.facebook.com 4
why1
why2
why1
music.google.com 2
image.google.com 3
map.yahoo.com 4
news.yahoo.com 7
而且./result是
music.facebook.com 8 6
但正如我所料,輸出應該是
music.facebook.com 8
image.facebook.com 4
why1
why2
why1
music.google.com 2
image.google.com 3
why1
why2
why1
map.yahoo.com 4
news.yahoo.com 7
why1
why2
why1
而且./result應該是:
music.facebook.com 8 6
image.google.com 3 2.5
news.yahoo.com 7 5.5
好像在loop A
位置,getline
回0
時dom
是google.com和yahoo.com。 爲什麼?
你可能想逃避比賽中的'.'。它符合任何角色。無論是「\」。「(除非需要是」\「。」')或'「[。]」';我會使用後者,因爲它不會引起有關要使用的反斜槓數量的尷尬問題。儘管如此,這與您的主要問題是切線的。 – 2012-07-18 16:07:52
當試圖調試意外的輸出時,首先要做的就是回顯輸入 - 所以你可以確定你得到了你期望的結果。您可能還需要顯示您正在使用的數據文件;我記得從y'day的問題(我的時間;今天早些時候在UTC)的一般情況,但其他人不會提供這些信息。此外,您應該可以顯示您期望的輸出內容。另外,我不相信像這樣過濾出來的東西是很好的'awk'風格。使用數組來保存數據,而不是文件。 – 2012-07-18 16:12:30
另請參見[如何在正則表達式中使用awk變量](http://stackoverflow.com/questions/11534173/how-to-use-awk-variables-in-regular-expressions/)。這是一個單獨的問題,但具有相同的一般背景。 – 2012-07-18 16:13:56