Web Hosting Talk







View Full Version : Help creating CSV file - shell scripting


innova
11-11-2005, 06:00 PM
I have a problem :)

I have a file, which contains one data entry per line. It looks like this:

item1+item2+item3+item4

You could say, its plus-delimited. The delimiter is arbitrary, could be a colon, pipe, etc.

What I want to do is convert it to standard CSV format:

"item1","item2","item3","item4"

Obviously, using tr to replace plusses with commas is trivial. I am not sure how to enclose each field with quotes, however. I have been over sed, awk, and various combos of unix utilities without figuring an easy way to do this. I could step over each line in a loop, then over each field, but that seems like an AWFUL lotta work for something that should seem trivial.

For the curious, this data will eventually find its way into mysql. I am aware that I can import data that isnt in CSV format directly, by telling mysql that I am using <arbitrary> delimiter. However, for the sake of uniformity I wish to have this data in CSV.

Anyone have any ideas?

Oras
11-11-2005, 07:09 PM
If I understood you will, you can make a simple PHP script to do this:
<?PHP
$file=file($string_file_name);
foreach($file as $data){
$csv.="\"".string_replace("+",","$data)."\"\n"; // Where + is your delimiter, & you can make another line with another delimiter
}
// Now write the $csv to a file like: filename.csv
?>
but I don't know how to do it in shell.
Wish this help
Regards