Imagine a text file where each csv record may have different numbers of fields. The task is to write code to output how many fields there are in each record of the file. You can assume there is no header line in the file and can read in from a file or standard input, as you choose.
You can assume a version of rfc4180 for the csv rules which I will explain below for the definition of each line of the file. Here is a lightly edited version of the relevant part of the spec:
Definition of the CSV Format
Each record is located on a separate line, delimited by a line break (CRLF). For example:
aaa,bbb,ccc CRLF zzz,yyy,xxx CRLF
The last record in the file may or may not have an ending line break. For example:
aaa,bbb,ccc CRLF zzz,yyy,xxx
(Rule 3. does not apply in this challenge)
Within each record, there may be one or more fields, separated by commas. Spaces are considered part of a field and should not be ignored.
Each field may or may not be enclosed in double quotes. If fields are not enclosed with double quotes, then double quotes may not appear inside the fields. For example:
"aaa","bbb","ccc" CRLF zzz,yyy,xxx
Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. For example:
"aaa","b CRLF bb","ccc" CRLF zzz,yyy,xxx
If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:
,"Hello, World!" "aaa","b""bb","ccc" zzz,yyy, "aaa","b bb","ccc","fish",""
Should give the output:
2, 3, 3, 5
Your can give the output values in any way you find most convenient.
You can use any library you like.
Awesome answers so far but we are missing a command line/bash answer which would be particularly cool.