如何在不指定年份的字符串中添加隐含年份?

时间:2011-02-23 20:57:28

标签: mysql perl sed awk

我必须从网站下载许多文本文件。然后我必须将它放入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是当前的当年),然后再将其放入数据库。
我怎么能这样做?

5 个答案:

答案 0 :(得分: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 :(得分:2)

一个小高尔夫球场的解决方案:

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

答案 2 :(得分:1)

year=`date +%Y`
sed "s|^\([0-9][0-9]/[0-9][0-9]\) |\1/$year |" filename

答案 3 :(得分: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'

答案 4 :(得分: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