在 AWK 中转换日期 [英] Converting dates in AWK
问题描述
我有一个包含多列文本的文件,包括沿 Fri Jan 02 18:23
行的时间戳,我需要将该日期转换为 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 的标准日期"工具来进行转换,但我无法弄清楚如何以它期望的格式将字段传递到日期"命令中(引用为" 或 's,) 因为 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.
类似"date -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屋!