Linux Galaxy

Convert Date Formats in a Text file with Perl

Posted on Jan 15, 2022 by kingbeowulf



A query was posted recently on a list on how to convert date formats in the form of "month/day/year" into a more standard unambiguous "year-month-day". I dabbled in Perl a very long time ago and so thought I'd take a look. After searching the Internet and some practice, here is my stab at it. For an example csv text file, for tabular data in this case:

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

The following Perl script will flip the order.

 1#!/usr/bin/perl
 2
 3# searches for xx/yy/zzzz (month/day/year) date pattern and converts 
 4# to zzzz-xx-yy in a text file (csv in this case).
 5
 6open(FH,"myfile.csv") or die "Can’t open file-$1";
 7open(WH,">new_myfile.csv") or die "Can’t open file in write mode- $!";
 8
 9while(my $line = <FH>){
10               $line =~s/(\d{2})\/(\d{2})\/(\d{4})/$3-$1-$2/g;
11               print WH $line;
12}
13	   
14close(FH);
15close(WH);

We now have:

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

Return to blog

King Beowulf's Linux Adventures


Contact:

  • kingbeowulf@linuxgalaxy.org
  • mumble.linuxgalaxy.org:64738
  • Libera.chat IRC
    • ##slackware, #slackbuilds, #linuxgalaxy

Screamin' and a-streamin' !

  • https://twitch.tv/kngbwlf
  • https://www.youtube.com/@mylinuxgalaxy

Advertisement

Try a nice upgrade from EVGA and get a discount!

Tired of Steam, Epic and other rip-off game "stores"? Check out Humble Bundle for your digital download needs! A portion of your hard-earned gaming cash goes to charity.

King Beowulf's Humble Bundle Referral Code

Citizen Science!