How to seperate text and adjust format like this?

in example.txt file is below

ADD PDU:SRN=0,PDUID=LOCAL,NAME="PDU_0",PSV=LOW,MOG="PUBLIC",REFERABLE=YES;
ADD PDU:SRN=2,PDUID=LOCAL,NAME="PDU_1",PSV=LOW,MOG="PUBLIC",REFERABLE=YES;
ADD MODULE:MID=84,MT=DSU,SRN1=0,SN1=4,MNAME="DSU84";
ADD MODULE:MID=85,MT=DSU,SRN1=0,SN1=4,MNAME="DSU85";

How to adjust format like below ? please help to give me the idea. Thanks

ADD PDU:SRN,PDUID,NAME,PSV,MOG,REFERABLE
0,LOCAL,"PDU_0",LOW,"PUBLIC",YES
2,LOCAL,"PDU_1",LOW,"PUBLIC",YES

ADD MODULE:MID,MT,SRN1,SN1,MNAME
84,DSU,0,4,"DSU84"
85,DSU,0,4,"DSU85"

What operating system are you using?

What shell are you using?

What have you tried to solve this on your own?

Is this a homework assignment? If not, what is the reason for doing this?

Do all "records" for a given ADD XXX have the same comma separated fields following them in the same order (as in your examples), or can some fields be missing or in a different order on some records?

Are all records for a given ADD XXX [/ICODE] pair adjacent (as in your examples), or can record types be separated? If they can be separated, is the output supposed to be grouped by record type or is the order of output records supposed to be the same as the order of the input records?

Let's give it a go:
Save as process.pl .
Run as perl process.pl example.txt

my %labels;

while(<>){
 my ($label, $csvs) = split /[:;]/;
 my @pairs = split ',', $csvs;
 my @titles, my @values;
 for(@pairs){
   my ($title, $value) = split '=';
   push @titles, $title;
   push @values, $value;
 }
 $labels{$label}[0] = join ',', @titles;
 push @{$labels{$label}}, join ',', @values;

}
for(keys %labels){
  print "$_:";
  for(@{$labels{$_}}){
    print"$_\n";
  }
  print "\n";
}

Output:

ADD PDU:SRN,PDUID,NAME,PSV,MOG,REFERABLE
0,LOCAL,"PDU_0",LOW,"PUBLIC",YES
2,LOCAL,"PDU_1",LOW,"PUBLIC",YES

ADD MODULE:MID,MT,SRN1,SN1,MNAME
84,DSU,0,4,"DSU84"
85,DSU,0,4,"DSU85"



1 Like