2011-02-23 26 views
2

我必须从网站下载许多文本文件。然后,我必须把它放到一个MySQL数据库,但该文件的形式行:如何将隐含年份添加到不指定年份的字符串?

02/04 15:00 Some strings 

03/03 15:00 other strings 

01/12/2010 12:00 other strings 

03/04 15:00 more strings 

... 

当年度不明确写入,这意味着它是当前年份。所以我需要逐行解析文件,并在将数据放入数据库之前,将表格dd/mm的每个日期转换为格式为dd/mm/yyyy(其中yyyy是当前年份)的日期。
我该怎么做?

+1

当前时间是1月1日00:00或接近那个时间时,你想要发生什么?它应该假定刚刚完成的一年或刚开始的一年? –

+0

无所谓。这并不重要。 – emanuele

回答

0
awk -v year=$(date +%Y) 'match($1, "^[0-9][0-9]/[0-9][0-9]$") {$1 = $1"/"year} 1'

awk -v year=$(date +%Y) 'split($1, a, "/") == 2 {$1 = $1"/"year} 1'

1
year=`date +%Y` 
sed "s|^\([0-9][0-9]/[0-9][0-9]\) |\1/$year |" filename 
2
#!/usr/bin/perl 
use strict; 
use warnings; 
use Time::Piece; 

my $pattern = qr(^(\d\d/\d\d));#month/day at start of line followed by space 
my $year = localtime->year; 

while (<DATA>){ 
    s/$pattern/$1\/$year /; 
    print; 
} 
__DATA__ 
02/04 15:00 Some strings 
03/03 15:00 other strings 
01/12/2010 12:00 other strings 
03/04 15:00 more strings 
+1

不需要所有这些未使用的临时变量:my $ year =(localtime)[5] + 1900; – tadmc

+1

您可以使用核心[Time :: Piece](http://search.cpan.org/perldoc?Time::Piece)模块简化本地时间处理。同样在替换中,您可以匹配一般空格并用空格替换。 – bvr

+0

我编辑了我的答案,以纳入上述建议。感谢@ tadmc和@bvr。我不知道Time :: Piece。 – d5e5

0
$ awk 'BEGIN{y=strftime("%Y")}length($1)==5{$1=$1"/"y}1' file 
02/04/2011 15:00 Some strings 
03/03/2011 15:00 other strings 
01/12/2010 12:00 other strings 
03/04/2011 15:00 more strings 

$ ruby -ane '$F[0].size==5 && $F[0]=$F[0]+"/"+Time.now.year.to_s;puts $F.join(" ")' file 
2

小golfy perl的溶液:

perl -MTime::Piece -pe '$yy=localtime->year; s{^(\d{2}/\d{2})(\s)}{$1/$yy$2}' input 
相关问题