Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex capture swap 1

Status
Not open for further replies.

leegold

Technical User
Mar 19, 2002
39
US
Below I'm just swapping 'Oct 1977' to '1977 Oct' it works OK. But I want to also change Oct to 10. So I want to process and swap so, 'Oct 1977' becomes '1977-10'.

Actually I want to change it to the form for a MYSQL date data type : 'YYYY-MM-DD'. So I also want to put in a dummy day so, 1977-10-01 is what I really want. How do I swap and process with regex?

Another hassel, It's a dirty file and there some fields that are just 1977 and I want 1977-01-01 in that case ...any help appreciated.

Lee G.
while (<INFILE>) {
chomp;
$zapvar = $_;
$zapvar =~
s/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(19\d{2})/$2 $1/;
print OUTFILE "$zapvar\n";
}
 
How's this?
Code:
#!perl
use strict;
use warnings;

my $newdate;

while (<DATA>) {
    chomp;
    if (/^([a-zA-Z]{3})\s+(\d\d\d\d)$/) { # mmm yyyy
        $newdate = qq($2-${\&cmth2int($1)}-01);
    } else {
        $newdate = qq($_-10-01); # assume it's just yyyy
    }
    print qq($newdate\n);
}

sub cmth2int {
    # Map char month mmm to 2-digit zero-filled dd.
    my ($char_month, $default) = (shift, shift || 10);
    my %months;
    my @monthnames = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
    @months{@monthnames} = map {sprintf qq(%02d), $_} (1..@monthnames);
    $months{$char_month} || $default;
}

__DATA__
Oct 1977
Jan 1986
1995
Aug 1961
2004
Apr 1066
Jun 2004
Xxx 2001

Output:
1977-10-01
1986-01-01
1995-10-01
1961-08-01
2004-10-01
1066-04-01
2004-06-01
2001-10-01

HTH
 
Thank you for the code!

I ended up using the DATE::MANIP module
...
my @format = '%Y-%m-%d';
...
$fields[3] = UnixDate($fields[3], @format);
...

 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top