在AWK转换日期 [英] Converting dates in AWK

查看:156
本文介绍了在AWK转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文本的多列的文件,包括沿周五02年1月18:23 ,我需要在该日期转换成<$ C的行时间戳$ C> MM / DD / YYYY HH:MM。格式

I have a file containing many columns of text, including a timestamp along the lines of Fri Jan 02 18:23 and I need to convert that date into MM/DD/YYYY HH:MM format.

我一直在尝试使用标准的'日期'工具使用awk函数getline做转换,但我不能完全弄清楚如何打发领域进入'日期'命令,预计格式(报价还是的,)作为函数getline需要用引号括起来过的命令字符串。

I have been trying to use the standard `date' tool with awk getline to do the conversion, but I can't quite figure out how to pass the fields into the 'date' command in the format it expects (quoted with " or 's,) as getline needs the command string enclosed in quotes too.

类似日期-d$ 1 $ 2 $ 3 $ 4'+'%D%H:%M'|函数getline VAR

现在,我想想,我想我真的问的是如何嵌入AWK变量为一个字符串。

Now that I think about it, I guess what I'm really asking is how to embed awk variables into a string.

推荐答案

你可以试试这个。假设你刚刚指定的日期是在文件

you can try this. Assuming just the date you specified is in the file

awk '
{
    cmd ="date \"+%m/%d/%Y %H:%M\" -d \""$1" "$2" "$3" "$4"\""
    cmd | getline var
    print var
    close(cmd)
}' file

输出

$ ./shell.sh
01/02/2010 18:23

如果你不使用GNU工具,就像如果你是在Solaris中,例如,使用NAWK

and if you are not using GNU tools, like if you are in Solaris for example, use nawk

nawk 'BEGIN{
   m=split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",d,"|")
   for(o=1;o<=m;o++){
      months[d[o]]=sprintf("%02d",o)
   }
   cmd="date +%Y"
   cmd|getline yr
   close(cmd)
}
{
    day=$3
    mth=months[$2]
    print mth"/"day"/"yr" "$4
} ' file

这篇关于在AWK转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆