Skip to content

Instantly share code, notes, and snippets.

@benhoyt
Last active January 23, 2023 08:54
Show Gist options
  • Save benhoyt/b043abcccca477b4bacbfb0dd72c1e21 to your computer and use it in GitHub Desktop.
Save benhoyt/b043abcccca477b4bacbfb0dd72c1e21 to your computer and use it in GitHub Desktop.
csvify: try to parse CSV with regular AWK
BEGIN {
FS = ","
}
{
nf = csvify(fields)
for (i=1; i<=nf; i++) {
printf "|%s|\n", fields[i]
}
print "---"
}
function csvify(fields, k, inquote, nf, i) {
for (k in fields) {
delete fields[k]
}
inquote = 0
nf = 0
for (i=1; i<=NF; i++) {
if (inquote) {
if (match($i, /[^"]"$/)) {
inquote = 0
sub(/"$/, "", $i)
gsub(/""/, "\"", $i)
nf++
fields[nf] = fields[nf] "," $i
} else {
gsub(/""/, "\"", $i)
fields[nf+1] = fields[nf+1] "," $i
}
} else {
if (match($i, /^"/)) {
inquote = 1
sub(/^"/, "", $i)
gsub(/""/, "\"", $i)
if (match($i, /"$/)) {
inquote = 0
sub(/"$/, "", $i)
nf++
fields[nf] = $i
} else {
fields[nf+1] = $i
}
} else {
nf++
fields[nf] = $i
}
}
}
return nf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment