in reply to Replace Whitespace with Comma

The Anon Monk solution is certainly something to consider. (update added: I see problems if this name field is way longer than your example. I suspect fixed column will wind up be the "way to go").

If you are making a .CSV file, then I think you will need to quote column 2, the name column. "DOE,JOHN" because with names, there could be titles, "DOE,JOHN,JR.", "DOE,JOHN,III", or other kinds of weirdness involving multiple commas which would throw off the parsing of the comma separated file. I would as a minor suggestion, skip blank lines on the input (sometimes these files wind up with a blank line at the end which is hard to see because it is invisible).

Anyway, one way below. I did add a test case where more than one field is missing.

#!/usr/bin/perl use strict; use warnings; while(<DATA>) { next if /^\s*$/; #skip blank lines s/^(\d+\s+)(\S+)(.+)/$1"$2"$3/; #quote column 2 s/\s{3,7}/,/g; print; } =prints: 12345,"DOE,JOHN",$50.00,REFUND,COMPLETE 12345,"DOE,JOHN",$25.00,DENIED,COMPLETE 12345,"DOE,JOHN",$75.00,,COMPLETE 12345,"DOE,JOHN",$10.00,REFUND,COMPLETE 12345,"DOE,JOHN",,,INCOMPLETE =cut __DATA__ 12345 DOE,JOHN $50.00 REFUND COMPLETE 12345 DOE,JOHN $25.00 DENIED COMPLETE 12345 DOE,JOHN $75.00 COMPLETE 12345 DOE,JOHN $10.00 REFUND COMPLETE 12345 DOE,JOHN INCOMPLETE
Update: as an extra thought, when I have a choice of separator character on these types of files, I usually choose "|" instead of "," - that is valid "CSV" and can be read by Excel. It is just easier to parse since there is no confusion about column separator vs embedded comma in quotes. A number of DB exported files that I work with come this way and its is a bit easier to fiddle with. However there are some excellent modules to parse "real" CSV - that parsing job way to complicated to try on your own.