Last active
January 23, 2023 08:54
-
-
Save benhoyt/b043abcccca477b4bacbfb0dd72c1e21 to your computer and use it in GitHub Desktop.
csvify: try to parse CSV with regular AWK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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