If there is only one data field that can contain commas, I would recommend a slightly different approach.

Split the line up on every comma.
Grab the last M fields from the back.
Grab the first N fields from the front.
Join whatever is left using commas into a single field
Join the three pieces together with tabs.

Here is a quick example to get you up to speed.

#!/usr/bin/perl use strict; my $line = 'john,doe,manager,Pepsi Cola, inc.,Detroit,Michigan'; my @fields = split(/,/,$line); # split on commas my @last2 = splice(@fields,-2); # Grab two fields off the back my @first3 = splice(@fields, 0,3); # Grab three fields from the front my @middle = @fields; # Whatever is left is the difficul +t "company" data my $middlefield = join(',',@middle); # join the middle portion back t +ogether print "First: $_\n" for (@first3); print "Middle: $_\n" for (@middle); print "Last: $_\n" for (@last2); print "\n"; my $newline = join("\t",@first3,$middlefield,@last2); # generate new +line print "Old: $line\n"; print "New: $newline\n";
I didn't quite understand your regex, but if you want to collapse multiple spaces down into a single one you might try s/\s+/ /g.

-Blake


In reply to Re: Help with substitution - - 15 Characters from the left by blakem
in thread Help with substitution - - 15 Characters from the left by La12

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.