It took me a while to see what your problem is. You have some fields in your original csv file that contain embedded line breaks, but there's no quoting or escaping provided, so a "normal" CSV parse won't work very well.

When a line ends with a comma, you're able to join it with the following line, by removing the line-break(s) after the comma. (But your regex does it wrong: it won't apply at all on LF-style data, it won't handle extra blank lines properly for CRLF-style data, and it removes the comma, which should be kept.)

When a line begins with a comma, you want to join it to the previous line, but the previous line has already been processed and written to output, so it's too late to fix that.

So, don't do it one line at a time - process the whole file as a single string:

perl -e '$/=undef; $_=<>; s/,[\r\n]+/,/g; s/[\r\n]+,/,/g; print' infil +e > infile.fxd
Those regexes preserve the commas, and handle any number of consecutive line breaks before or after a comma (for both LF and CRLF data).

(Note that I'm redirecting output to a different file, rather than replacing the original - that makes it easy to "try, try again" for cases like this, where you seldom get it right the first time. Once you get it right, then you can rename the output to replace the input.)

(Update: P.S.: Welcome to the Monastery!)

(Updated again to add remarks about LF vs. CRLF data)


In reply to Re: Auto correct a csv file by graff
in thread Auto correct a csv file by karthikAk

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.