<p>How do you parse a CSV file using gawk?  Simply setting <code>FS=","</code> is not enough, as a quoted field with a comma inside will be treated as multiple fields.</p>

<p>Example using <code>FS=","</code> which does not work:</p>

<p>file contents:</p>

<pre><code>one,two,"three, four",five
"six, seven",eight,"nine"
</code></pre>

<p>gawk script:</p>

<pre><code>BEGIN { FS="," }
{
  for (i=1; i&lt;=NF; i++) printf "field #%d: %s\n", i, $(i)
  printf "---------------------------\n"
}
</code></pre>

<p>bad output:</p>

<pre><code>field #1: one
field #2: two
field #3: "three
field #4:  four"
field #5: five
---------------------------
field #1: "six
field #2:  seven"
field #3: eight
field #4: "nine"
---------------------------
</code></pre>

<p>desired output:</p>

<pre><code>field #1: one
field #2: two
field #3: "three, four"
field #4: five
---------------------------
field #1: "six, seven"
field #2: eight
field #3: "nine"
---------------------------
</code></pre>

Here's what I came up with.  Any comments and/or better solutions would be appreciated.
```
```
BEGIN { FS="," }
{
  for (i=1; i<=NF; i++) {
    f[++n] = $i
    if (substr(f[n],1,1)=="\"") {
      while (substr(f[n], length(f[n]))!="\"" || substr(f[n], length(f[n])-1, 1)=="\\") {
        f[n] = sprintf("%s,%s", f[n], $(++i))
      }
    }
  }
  for (i=1; i<=n; i++) printf "field #%d: %s\n", i, f[i]
  print "----------------------------------\n"
}
```
```
The basic idea is that I loop through the fields, and any field which starts with a quote but does not end with a quote gets the next field appended to it.