date - getline,awk和日期(格式化日期)

标签 date awk getline

我正在尝试在CSV文件中格式化一些日期数据。

~/temperature$ cat m
1 01/04/13 02:20:07 PM 21.843 24.360 981.5   
2 01/04/13 02:25:07 PM 21.509 27.048 335.1   
3 01/04/13 02:30:07 PM 19.555 31.441 335.1   
4 01/04/13 02:35:07 PM 18.628 32.154 335.1   
5 01/04/13 02:40:07 PM 18.152 31.782 327.2   
6 01/04/13 02:45:07 PM 17.962 34.723 327.2   
7 01/04/13 02:50:07 PM 17.867 33.008 335.1   
8 01/04/13 02:55:07 PM 17.819 35.722 327.2   
9 01/04/13 03:00:07 PM 17.819 33.989 327.2   
10 01/04/13 03:05:07 PM 17.796 36.143 327.2

我想将日期转换为“YYYY-MM-DD HH:MM:SS”格式。

这是我尝试过的:
~/temperature$ awk '{("date \"+%Y-%m-%d %T\" --date \"$2 $3\"")|getline t; print t}' m
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00
2014-03-28 00:00:00

~/temperature$ awk '{("date \"+%Y-%m-%d %T\" -d "$2 )|getline t; print t}' m
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
2013-01-04 00:00:00
~/temperature$ awk '{("date \"+%Y-%m-%d %T\" -d "$2" "$3)|getline t; print t}' m
date: extra operand `02:20:07'
Try `date --help' for more information.

date: extra operand `02:25:07'
Try `date --help' for more information.

...
...

因此,这两种方法都给出了错误的日期。关于如何解决它的任何想法?
非常感谢。

DY。

最佳答案

这将工作:

$ awk '
{
    get_date = "date \"+%Y-%m-%d %T\" -d \""$2" "$3" "$4"\""
    get_date | getline new_date
    print new_date
}' file
2013-01-04 14:20:07
2013-01-04 14:25:07
2013-01-04 14:30:07
2013-01-04 14:35:07
2013-01-04 14:40:07
2013-01-04 14:45:07
2013-01-04 14:50:07
2013-01-04 14:55:07
2013-01-04 15:00:07
2013-01-04 15:05:07

关于date - getline,awk和日期(格式化日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22724393/

相关文章:

php - 如何在 PHP 中减去两个日期并在没有交互的情况下发送自动电子邮件

.net - 给定一个日期范围(开始日期和结束日期),我如何计算天数,不包括 .Net 中一周中的指定天数?

C++ 问题 - getline 跳过第一个输入

c++ - std::getline 和 posix 信号

date - 字符串到最新的groovy

javascript - 将日期值转换为时间戳 - 发布请求 - Ember.js

awk - 使用 awk 对多个文件中的同一列求和?

awk - 打印大文件中前 N 行满足特定条件的每一行

linux - bash 中的 awk 语句在 for 循环中不执行

c++ - 对字符串使用 cin 和 getline