Created
December 16, 2013 12:40
-
-
Save sokrato/7986374 to your computer and use it in GitHub Desktop.
convert rows to CSV, see http://stackoverflow.com/questions/20609952/create-a-csv-from-a-variable-length-newline-input
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
EGIN { | |
FIELD_LIST = "Field1,Field2,Field3"; # fields definition, in order | |
split(FIELD_LIST, fields, ","); | |
} | |
{ | |
pos = find(fields, $1); | |
if (pos == 0) { | |
print("unexpected field " $1); | |
exit 1; | |
} | |
if ($1 == fields[1] && NR>1) { # record start | |
echo_record(fields, rec); | |
split("", rec) | |
} | |
rec[$1] = $2; # store field value | |
} | |
END { | |
echo_record(fields, rec); | |
} | |
# find position of val in arr. 0 if not found | |
function find(arr, val) | |
{ | |
i=1; | |
for (idx in arr) { | |
if (arr[idx] == val) return i; | |
++i; | |
} | |
return 0; | |
} | |
function echo_record(fileds, record) | |
{ | |
start = 0 | |
for (key in fields) { | |
if (start) printf(", "); | |
start = 1; | |
val = record[fields[key]]; | |
if (val) printf("%s", val); | |
else printf(" "); | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment