Avatar of magento
magento
 asked on

Perl one line fix

Hi,

This is my input:

data1,data2,data5,data6,data3,data4
data1,data2,data5,data7,data9,data8

I want output as below ( spliting each line by 3 columns )

data1,data2,data5
data6,data3,data4
data1,data2,data5
data7,data9,data8

This the code i have tried:
But i am getting output excluding data5 , please advice

#!/usr/bin/perl
use strict;
use warnings;
my $file = shift or die "usage: $0 Inputfile";
open FH , $file or die "unable to open $file , $!";
my @data = map { chomp; $_ } <FH>;
#print join ("\n",@data);
foreach (@data) {
my @ds = split /data5,/, $_;
print $_ , "\n" for @ds;
}

Open in new window


Thanks,
Magento
Perl

Avatar of undefined
Last Comment
magento

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ozo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ozo

or
perl -pe 's/(?<=data5),/\n/' input
or
perl -F, -ane '$"=",";print "@F[0..2]\n@F[3..5]"' input
or
perl -pe '$"=s/(,.*?,.*?),/$1\n/' input
magento

ASKER
Hi Ozo ,

Worked as per my needs. Great thanks.

Can you advice what actually (?<=data5), does?

Thanks
ozo

perl -MYAPE::Regex::Explain -e 'print YAPE::Regex::Explain->new(qr/(?<=data5),/)->explain'
The regular expression:

(?-imsx:(?<=data5),)

matches as follows:
 
NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  (?<=                     look behind to see if there is:
----------------------------------------------------------------------
    data5                    'data5'
----------------------------------------------------------------------
  )                        end of look-behind
----------------------------------------------------------------------
  ,                        ','
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------
Your help has saved me hundreds of hours of internet surfing.
fblack61
magento

ASKER
Ozo , Many thanks for the explanation.