2016-03-19 74 views
0

我想使用awk更改從日誌文件中獲取的日期格式,如下所示。誰可以幫我這個事?awk從日誌文件更改日期格式

INPUT:

Feb 29 03:32:02 localhost.localdomain haproxy[12722]: xxx.xxx.xxx.xxx:46141 [29/Feb/2016:03:32:02.460] loadbalancer 0/0/0/23/23 304 197 - - --VN 29/2/0/0/0 0/0 {Mozilla/5.0 (Linux; Android 5.0.1; ALE-L21 Build/HuaweiALE-L21) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36} "GET xxxxxxxxxxxxxxxxxxxxxxxxxxxxx HTTP/1.1" 
Feb 29 03:32:02 localhost.localdomain haproxy[12722]: xxx.xxx.xxx.xxx:46141 [29/Feb/2016:03:32:02.460] loadbalancer 0/0/0/23/23 304 197 - - --VN 29/2/0/0/0 0/0 {Mozilla/5.0 (Linux; Android 5.0.1; ALE-L21 Build/HuaweiALE-L21) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36} "GET xxxxxxxxxxxxxxxxxxxxxxxxxxxxx HTTP/1.1" 

預期輸出:

2016-02-29 03:32:02 localhost.localdomain haproxy[12722]: xxx.xxx.xxx.xxx:46141 [29/Feb/2016:03:32:02.460] loadbalancer 0/0/0/23/23 304 197 - - --VN 29/2/0/0/0 0/0 {Mozilla/5.0 (Linux; Android 5.0.1; ALE-L21 Build/HuaweiALE-L21) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36} "GET xxxxxxxxxxxxxxxxxxxxxxxxxxxxx HTTP/1.1" 
2016-02-29 03:32:02 localhost.localdomain haproxy[12722]: xxx.xxx.xxx.xxx:46141 [29/Feb/2016:03:32:02.460] loadbalancer 0/0/0/23/23 304 197 - - --VN 29/2/0/0/0 0/0 {Mozilla/5.0 (Linux; Android 5.0.1; ALE-L21 Build/HuaweiALE-L21) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36} "GET xxxxxxxxxxxxxxxxxxxxxxxxxxxxx HTTP/1.1" 

=========================== ==================================== 使用的命令(錯誤的語法):

# awk ' 
{ 
logdate=$1" "$2" "$3; 
changedate="date -d "'"logdate"'" +\"%Y-%m-%d %T\""; 
changedate | getline var; 
gsub (logdate,var); 
print var;`enter code here` 
}' test.log 

錯誤輸出:

date: extra operand ‘03:32:02’ 
Try 'date --help' for more information. 

date: extra operand ‘03:32:02’ 
Try 'date --help' for more information. 
+1

謝謝埃德莫頓格式化查詢... – skumble

回答

1

如果不需要用awk,一個簡單的shell循環將工作:

while read mon day rest; do 
    printf "%s %s\n" "$(date -d "$mon $day" +%F)" "$rest" 
done < file.log 

如果必須用awk,它不是真的有必要調出日期爲每一行:

awk ' 
    BEGIN { 
     split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", m) 
     for (i=1; i <= 12; i++) mon[m[i]] = i 
    } 
    { 
     $1 = sprintf("2016-%02d", mon[$1]) 
     sub(/ /,"-") 
     print 
    } 
' file.log 
+0

感謝格倫的腳本... – skumble