Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reformat text in perl

Tags:

awk

perl

I have a file of 1000 lines, each line in the format

filename dd/mm/yyyy hh:mm:ss

I want to convert it to read

filename mmddhhmm.ss

been attempting to do this in perl and awk - no success - would appreciate any help

thanks

like image 432
paul44 Avatar asked Dec 04 '25 19:12

paul44


2 Answers

You can do a simple regular expression replacement if the format is really fixed:

s|(..)/(..)/.... (..):(..):(..)$|$2$1$3$4.$5|

I used | as a separator so that I do not need to escape the slashes.

You can use this with Perl on the shell in place:

perl -pi -e 's|(..)/(..)/.... (..):(..):(..)$|$2$1$3$4.$5|' file

(Look up the option descriptions with man perlrun).

like image 130
Svante Avatar answered Dec 06 '25 11:12

Svante


Another somehow ugly approach: foreach line of code ($str here) you get from the file do something like this:

my $str = 'filename 26/12/2010 21:09:12';

my @arr1 = split(' ',$str);
my @arr2 = split('/',$arr1[1]);
my @arr3 = split(':',$arr1[2]);

my $day = $arr2[0]; 
my $month = $arr2[1]; 
my $year = $arr2[2];

my $hours = $arr3[0]; 
my $minutes = $arr3[1]; 
my $seconds = $arr3[2];

print $arr1[0].' '.$month.$day.$year.$hours.$minutes.'.'.$seconds;
like image 22
Thariama Avatar answered Dec 06 '25 09:12

Thariama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!