awk命令转换文件中的日期格式 [英] awk command to convert date format in a file
问题描述
以下是文件内容和所用的awk命令:
Given below is the file content and the awk command used:
输入文件:in_t.txt
1,ABC,SSS,20-OCT-16,4,1,0,5,0,0,0,0
2,DEF,AAA,20-JUL-16,4,1,0,5,0,0,0,0
预期的外部文件:
SSS|2016-10-20,5
AAA|2016-07-20,5
我尝试了以下命令:
awk -F , '{print $3"|"$(date -d 4)","$8}' in_t.txt
将外档设为:
SSS|20-OCT-16,5
AAA|20-JUL-16,5
我只想知道如何使用相同的awk命令格式化日期.尝试过
Only thing I want to know is on how to format the date with the same awk command. Tried with
awk -F , '{print $3"|"$(date -d 4)","$8 +%Y-%m-%d}' in_t.txt
正在获取语法错误.我可以在这方面寻求帮助吗?
Getting syntax error. Can I please get some help on this?
推荐答案
单个命令的定义是什么?调用awk是单个shell命令.这可能就是您想要的:
What's your definition of a single command? A call to awk is a single shell command. This may be what you want:
$ awk -F'[,-]' '{ printf "%s|20%02d-%02d-%02d,%s\n", $3, $6, (match("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC",$5)+2)/3, $4, $10 }' file
SSS|2016-10-20,5
AAA|2016-07-20,5
顺便说一句,重要的是要记住 awk不是shell .您不能像直接从C中那样直接从awk调用shell工具(例如date
).当您编写$(date -d 4)
时,awk看到了一个未设置的名为date
(数值0
)的变量,该变量是从中提取的名为d
(也称为0
)的未设置变量的值,以获取数字结果0
,然后将其与数字4
连接以获取04
,然后应用$
运算符以获取字段$04
(= $4
)的内容.输出与shell命令date
无关.
BTW it's important to remember that awk is not shell. You can't call shell tools (e.g. date
) directly from awk any more than you could from C. When you wrote $(date -d 4)
awk saw an unset variable named date
(numeric value 0
) from which you extracted the value of an unset variable named d
(also 0
) to get the numeric result 0
which you then concatenated with the number 4
to get 04
and then applied the $
operator to to get the contents of field $04
(=$4
). The output has nothing to do with the shell command date
.
这篇关于awk命令转换文件中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!