我有一个CSV文件,其日期时间格式如下:
8/2/2012 1:34:01 PM
我需要查找此类日期的所有事件(可能是正则表达式)并将其(在文件中)转换为mysql默认日期时间格式(2012-08-02 13:34:01)。
我找到了
date --date="8/2/2012 1:34:01 PM" +"%F %T"
工作正常,我得到了正确的结果。解决方案是找到所有错误格式化的日期,并通过上述日期函数传递它。
CSV文件中的单行如下所示:
"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","10/31/2012 10:02:03 AM","1/29/1999 1:54:50 PM","11/6/2012 8:47:01 PM","S"
非常感谢!
答案 0 :(得分:2)
这对你好吗?
awk -F, -vOFS=',' '{for (i=7;i<=9;i++) {"date --date="$i" +\"%F %T\"" |getline $i;$i="\""$i"\""}}1' file
用那条线测试:
kent$ echo '"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","10/31/2012 10:02:03 AM","1/29/1999 1:54:50 PM","11/6/2012 8:47:01 PM","S"'|awk -F, -vOFS=',' '{for (i=7;i<=9;i++) {"date --date="$i" +\"%F %T\"" |getline $i;$i="\""$i"\""}}1'
"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","2012-10-31 10:02:03","1999-01-29 13:54:50","2012-11-06 20:47:01","S"
答案 1 :(得分:0)
如果使用perl是一个选项,这应符合您的要求
#! /usr/bin/perl
use strict;
use warnings;
while (my($m, $d, $y, $H, $M, $S, $a) = m!\"(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)\s+([ap]m)\"!i) {
$H += 12 if ($a =~ m/pm/i);
my $dt = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $y, $m, $d, $H, $M, $S);
s!!$dt!;
}
用
调用它perl -i.bak -p convert.pl csv.txt
这会将日期转换为MySQL格式。它还会创建备份文件csv.txt.bak
。
答案 2 :(得分:0)
我使用带有适当CSV解析器的工具。这是一个红宝石的例子
ruby -e '
require "csv"
require "date"
def format_date(date)
DateTime.strptime(date, "%m/%d/%Y %r").strftime "%Y-%m-%d %T"
end
CSV.foreach ARGV[0] do |row|
[6,7,8].each {|i| row[i] = format_date row[i]}
puts CSV.generate_line row, {:force_quotes => true}
end
' file.csv
根据您的样本输入,此输出
"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","2012-10-31 10:02:03","1999-01-29 13:54:50","2012-11-06 20:47:01","S"