Friday, October 24, 2008

Converting a space delimited file to a CSV file

Here is a little quick conversion script I wrote today. I needed to import data from another utility into OpenOffice's Calc. But the output from this other utility was not tab separated like I thought it was. It had a variable number of spaces between each field. So, here is my handy conversion:



You invoke the script like this:

ruby convert_to_csv.rb infile > outfile

So, we take the command line argument infile, open it, and then iterate through each line. In each line, we use the gsub command to substitute a comma for any whitespace (tab, space, newline, etc.). The chop method is used because after running the line through the gsub command, the newline is converted to a comma. We want to change that back to a newline, so, therefore, we chop it off, and then append our newline.

No comments: