awk从日志文件更改日期格式

时间:2016-03-19 21:02:55

标签: date awk format

我想使用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 个答案:

答案 0 :(得分: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