Reformat text in 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

tried to do this in perl and awk - without success - would appreciate any help

thank

+3
source share
4 answers

You can perform the usual regex replacement if the format is really fixed:

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

I used |as a delimiter, so I did not have to remove slashes.

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

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

(See option descriptions with man perlrun).

+4
source

Another ugly approach: foreach line of code ($ str here) that 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;
+1

perl script

while( my line = <> ){
    if ( $line =~ /(\S+)\s+\(d{2})\/(\d{2})/\d{4}\s+(\d{2}):(\d{2}):(\d{2})/ ) {
        print $1 . " " . $3 . $2 . $4 . $5 . '.' . $6;
    }
}

, . , : ( >= 1) >= 1 (2digits)/(2digits)/4digits whitepsace >= 1 (2digits):( 2digits):( 2digits)

Capture groups are in () with numbers from 1 to 6 from left to right.

+1
source

Usage sed:

sed -r 's|/[0-9]{4} ||; s|/||; s/://; s/:/./' file.txt
  • delete year /yyyy
  • delete the remaining trait
  • remove the first colon
  • change the remaining colon to a point

Usage awk:

awk '{split($2,d,"/"); split($3,t,":"); print $1, d[1] d[2] t[1] t[2] "." t[3]}'
0
source

Source: https://habr.com/ru/post/1749386/


All Articles