2013-01-11 29 views
1
INFO #my-service# #add# id=67986324423 isTrial=true 
INFO #my-service# #add# id=43536343643 isTrial=false 
INFO #my-service# #add# id=43634636365 isTrial=true 
INFO #my-service# #add# id=67986324423 isTrial=true 
INFO #my-service# #delete# id=43634636365 isTrial=true 
INFO #my-service# #delete# id=56543435355 isTrial=false 

我想指望它有與#add#屬性的唯一ID在他們&有isTrial=true線。如何使用陣列使用awk在Linux中

這是我目前的解決方案,我想知道爲什麼我的陣列不打印

BEGIN { print "Begin Processing of various Records"} 

{if($3~"add" && $5~"true") 
    { 
    ++i; 
    if($4 not in arr){arr[i]=$4;++j} 
    } 
    {print $0} 
} 

END {print "Process Complete:--------"j} 

回答

1

您需要測試,看看第四場是不是已經在陣列中,像這樣:

BEGIN { 
    print "Begin Processing of various Records" 
} 

$3 ~ /add/ && $5 ~ /true/ && !a[$4]++ { 

    i++ 
    print 
} 

END { 
    print "Process Complete. Records found:", i 
} 

結果:

Begin Processing of various Records 
INFO #my-service# #add# id=67986324423 isTrial=true 
INFO #my-service# #add# id=43634636365 isTrial=true 
Process Complete. Records found: 2 

Here's some info您可能會感興趣。 HTH。


按照下面的評論,你也可以這樣做:

BEGIN { 
    print "Begin Processing of various Records" 
} 

$3 ~ /add/ && $5 ~ /true/ && !a[$4] { 

    a[$4]++ 
    print 
} 

END { 
    print "Process Complete. Records found:", length(a) 
} 

請注意,這是非常不同:

BEGIN { 
    print "Begin Processing of various Records" 
} 

$3 ~ /add/ && $5 ~ /true/ && !a[$4] { 

    # See the line below. I may not have made it clear in the comments that 
    # you can indeed add things to an array without assigning the key a 
    # value. However, in this case, this line of code will fail because our 
    # test above (!a[$4]) is testing for an absence of value associated 
    # with that key. And the line below is never assigning a value to the key! 
    # So it just won't work. 

    a[$4] 


    # Technically, you don't need to increment the value of the key, this would 
    # also work, if you uncomment the line: 

    # a[$1]=1 

    print 
} 

END { 
    print "Process Complete. Records found:", length(a) 
} 
+0

你能解釋一下這是什麼意思'!a [$ 4] ++' – user175386049

+0

當然。它只是意味着:'如果字段4不是(!)在一個數組(稱爲a)中,將它添加到數組中,將該鍵的值遞增1(++)'。那有意義嗎?第四個字段是數組的關鍵。 – Steve

+0

我沒有得到++部分,我沒有得到什麼部分是將4美元添加到數組,以及哪部分是遞增密鑰 – user175386049

1
grep '#add#.*isTrial=true' input | sed 's/[^=]*=\([^ ]*\).*/\1/' | sort | uniq -c 
+0

其實我我正在學習awk,所以我想要awk解決方案 學習。感謝那 – user175386049

1

一種方法用awk:

$ awk '$3 ~ /add/ && $5 ~ /true/{sub(/.*=/,"",$4);a[$4]++;}END{for (i in a)print i, a[i];}' file 
43634636365 1 
67986324423 2 

關於您的解決方案:

  1. 當您使用contains(~)運算符,該模式應始終以斜槓(//)提供,而不是直接用雙引號括起來。

  2. 當您檢查$4 not in arr時,它檢查陣列鍵中的$ 4,而您將$ 4作爲數組值arr[i]=$4填充。

+0

你能糾正我的腳本,以便我看到多遠我從解決方案 – user175386049

0
awk '$5~/isTrial=true/ && $3~/#add#/{a[$4]}END{for(i in a){count++}print count}' 

測試here