On 13 Jun 12:35, Ted Harding wrote:
On 13-Jun-11 11:02:16, Brett Parker wrote:
I would *never* suggest parsing csv in bash. Ever. Python's csv module is lovely, and perl's DBD::CSV is fine. Awk hasn't got a csv parser,
Err, I respectfully disagree ... (in other words, b*****ks)!
Copy the following into a console:
awk 'BEGIN{FS=","; i=0}; {i=i+1; print $i}' << EOT Row 1,Field 1.1,Field 1.2,Field 1.3 Row 2,Field 2.1,Field 2.2,Field 2.3 Row 3,Field 3.1,Field 3.2,Field 3.3 Row 4,Field 4.1,Field 4.2,Field 4.3 EOT
and you will get:
Row 1 Field 2.1 Field 3.2 Field 4.3
(printing field i=1 from line 1, field i=2 from line 2, ... ).
So awk has parsed the CSV! The trick is to set the Field Separator (FS=",") to comma. After that you can do what you like.
I respectfully call you a fucking moron and ask you what happens if your csv does something like:
"Row 1","This is a description, it's quite long and contains commas",97 "Row 2","This is a different description without commas",12
Now, please, ffs, learn that just because it's comma seperated doesn't mean that the field doesn't contain commas. The number of times I've sat and had to debug someone elses shitty code because rather than using a csv library that's been tested they decided that they could just split on commas is no longer funny. And when people turn up on a list with a lot of technical people on it suggesting doing just this it makes me Very Angry. And you don't want to see me angry.