On 1/14/22 13:13, Rich Shepard wrote:
> I often download data as .csv files. The dates are usually formated as
> mm/dd/yyyy. I want to convert them to the format yyyy-mm-dd.

Rich,

I may not have this quite right as I haven't touched Perl in ages.  From
a few online hints:

myfile.csv (month/day/year)

COLA,DATE,COLB,COLC
xxxx,12/15/2021,xxxx,xxxx
xxxx,01/14/2022,xxxx,xxxx

---------------------------

#!/usr/bin/perl -w

open(FH,"myfile.csv") or die "Can’t open file-$1";
open(WH,">new_myfile.csv") or die "Can’t open file in write mode- $!";

while(my $line = <FH>){
               $line =~s/(\d{2})\/(\d{2})\/(\d{4})/$3-$1-$2/g;
               print WH $line;
}
      
close(FH);
close(WH);

--------------------------

new_myfile.csv (year-month-day)

COLA,DATE,COLB,COLC
xxxx,2021-12-15,xxxx,xxxx
xxxx,2022-01-14,xxxx,xxxx

This uses search with regular expressions so, I think, you don't need to
know what column its in. Not quite sure I've got the regex quite right
since I don't know what else might match the xx/yy/zzz date pattern.

-Ed


Reply via email to