Skip to content

Instantly share code, notes, and snippets.

@sokrato
Created December 16, 2013 12:40
Show Gist options
  • Save sokrato/7986374 to your computer and use it in GitHub Desktop.
Save sokrato/7986374 to your computer and use it in GitHub Desktop.
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