2012-03-18 60 views
1

以下awk代碼按預期工作。 我想檢查第二個字段$ 2是否爲0,並使用「setex」命令而不是默認的「hincrby」。awk中的比較

BEGIN { 
    # all fields are separated by^
    FS = "^"; 
} 
{ 
    # $7 is the date and time in the form yyyy-mm-dd hh:mm:ss. 
    # Split at colons to get hours minutes and seconds into a[1] 
    # through a[3]. Round minutes to nearest 5. 
    split($7, a, ":"); 
    split(gensub(/-/,"","g",$7),b,"~"); 
    a[2] = int(a[2]); 
    printf "hincrby r:%s:%s %s:%02d:00 1\\r\\n\n zadd RequestSet %s r:%s:%s\\r\\n\n ", $1, $2, a[1], a[2], b[1], $1, $2; 
} 

上面的代碼將輸出像這樣...

hincrby r:565:14718 2012-03-10~12:55:00 1\r\n zadd RequestSet 20120310 r:565:14718\r\n 

如果creativeid是0,那麼預期的輸出如下:

hincrby r:565:0 2012-03-10~12:55:00 1\r\n zadd RequestSet 20120310 r:565:14718\r\n hincrby r:565:14718 nods 1\r\n 

對於所有其他creativeids($ 2) ,我需要用完整日期生成的另一個聲明($ 7)

hincrby r:565:14718 2012-03-10~12:55:00 1\r\n zadd RequestSet 20120310 r:565:14718\r\n setex xyzabc:r 172800 2012-03-10~12:59:49\r\n 

換句話說,我想寫以下PHP邏輯的awk

if($creativeid !=0){    
     $pipe->setex($cb.':r','172800',$datetime); 
    }else{ 
     $pipe->hincrby("r:".$zone.":".$creativeid,'nods',1); 
    } 

更新:

以下的if-then-else的代碼似乎並沒有工作:

if $2 = 0 
printf "hincrby r:%s:%s %s:%02d:00 1\\r\\n\n zadd RequestSet %s r:%s:%s\\r\\n\n hincrby r:%s:%s nods 1\r\n", $1, $2, a[1], a[2], b[1], $1, $2, $1, $2; 
else 
printf "hincrby r:%s:%s %s:%02d:00 1\\r\\n\n zadd RequestSet %s r:%s:%s\\r\\n\n setex %s:r 172800 %s", $1, $2, a[1], a[2], b[1], $1, $2, $5, $7; 
+1

在大多數語言中,它被稱爲'if'在AWK了。你怎麼了? – 2012-03-18 12:21:44

回答

2
cmd = (a[2] == 0) ? "hincrby" : "setx" 
print cmd  

# or 

if(a[2] == 0) print "hincrby" 
else print "setx" 

a[2]=0總是是真實的。它只是一個任務...
a[2]="anything"將是真實的,除非它是一個無效值。

注意if(a[2]=0)確實變化a[2]值...

0

if($ 2 = 0)解決了這個問題。感謝提示。

+1

不,您正在將0分配給數據的第二個字段。要測試它是否等於零,你需要使用'if $(2 == 0)...'。注意2'='標誌。祝你好運。 – shellter 2012-03-18 14:13:05