| 1 |
# tocsv.awk --- convert data to CSV format |
| 2 |
# |
| 3 |
# Arnold Robbins, [email protected], Public Domain |
| 4 |
# April 2023 |
| 5 |
|
| 6 |
function tocsv(fields, sep, i, j, nfields, result) |
| 7 |
{ |
| 8 |
if (length(fields) == 0) |
| 9 |
return "" |
| 10 |
|
| 11 |
if (sep == "") |
| 12 |
sep = "," |
| 13 |
delete nfields |
| 14 |
for (i = 1; i in fields; i++) { |
| 15 |
nfields[i] = fields[i] |
| 16 |
if (nfields[i] ~ /["\n]/ || index(nfields[i], sep) != 0) { |
| 17 |
gsub(/"/, "\"\"", nfields[i]) # double up the double quotes |
| 18 |
nfields[i] = "\"" nfields[i] "\"" # wrap in double quotes |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
result = nfields[1] |
| 23 |
j = length(nfields) |
| 24 |
for (i = 2; i <= j; i++) |
| 25 |
result = result sep nfields[i] |
| 26 |
|
| 27 |
return result |
| 28 |
} |
| 29 |
function tocsv_rec(sep, i, fields) |
| 30 |
{ |
| 31 |
delete fields |
| 32 |
for (i = 1; i <= NF; i++) |
| 33 |
fields[i] = $i |
| 34 |
|
| 35 |
return tocsv(fields, sep) |
| 36 |
} |