use strict; use warnings; my $line; while () { if (/^\s*MSISDN=(\d+);/) { print "$line\n" if defined $line; $line = $1 ; } if (/\s*CF=([\w-]+?-(?:NONE|\d+))/) { my $add = $1; $add =~ s{(\d+)$}{1/1/1/$1}; $add =~ s{NONE}{1/1/1/0}; $line .= ",$add"; } } print "$line\n"; __DATA__ # --> Here, the data with two record blocks you presented just above #### 436906901235,CFU-ALL-PROV-1/1/1/0,CFB-ALL-PROV-1/1/1/0,CFNRY-ALL-PROV-1/1/1/0,CFNRC-ALL-PROV-1/1/1/0,CFD-TS10-ACT-1/1/1/91436903000 436906901231,CFU-ALL-PROV-1/1/1/0,CFB-ALL-PROV-1/1/1/0,CFNRY-ALL-PROV-1/1/1/0,CFNRC-ALL-PROV-1/1/1/0,CFD-TS10-ACT-1/1/1/91436903000