#! perl -slw use strict; my @lines = ; ## Pass 1. OR the records with a mask of spaces my $mask = chr(32) x length $lines[ 0 ]; $mask |= $_ for @lines; ## Detect the spaces that remain and build the template my $templ = ''; $templ .= 'a' . length( $1 ) . 'x' . length( $2 ) . ' ' while $mask =~ m[(\S+)(\s+|$)]g; $templ =~ s[x\d+\s+$][]; ## Strip redundant last 'xN' print $templ; ## Split the records and output delimited by '|' print join '|', unpack $templ, $_ for @lines; __DATA__ The First One Here Is Longer. Collie SN 262287630 77312 93871 MVP A Second (PART) here First In 20 MT 169287655 506666 61066 RTD 3rd Person "Something" X&Y No SH 564287705 45423 52443 RTE The Fourth Person 20 MLP 4000 360505504 3530 72201 VRE The Fifth Name OR Something Twin 200 SH 469505179 3530 72201 VRE The Sixth Person OR Item MLP 260505174 3,530 72,201 VRE 70 The Seventh Record MLP 764205122 3530 72201 VRE The Eighth Person MLP MLP 160545154 3530 7220 VRE #### a29x1 a11x1 a2x1 a9x2 a6x2 a6x2 a4 The First One Here Is Longer.|Collie SN | |262287630|77312 | 93871|MVP A Second (PART) here |First In 20|MT|169287655|506666| 61066|RTD 3rd Person "Something" |X&Y No SH | |564287705|45423 | 52443|RTE The Fourth Person 20 |MLP 4000 | |360505504|3530 | 72201|VRE The Fifth Name OR Something |Twin 200 SH| |469505179|3530 | 72201|VRE The Sixth Person OR Item |MLP | |260505174|3,530 |72,201|VRE 70 The Seventh Record |MLP | |764205122|3530 | 72201|VRE The Eighth Person MLP |MLP | |160545154|3530 | 7220|VRE