i am v new to awk, well unix as a whole really but im enjoying it alot...
im trying to extract some data from a file, and parsing it into arrays, ive trawled for hours on the internet and cant find much when it comes to awk and arrays??
anyway, heres the file:
tableA tableB tableC
1 1 3
2 3 2
3 2 1
tableD tableE tableF
4 4 6
5 6 5
6 3 4
i want to loop through this data, putting the array/array index name as tableA, B, C etc, and then have the numbers as elements of the each array, my long term hope is to pipe these out to a file, where they can perform some kind of sql statement, something like UPDATE tableA where field = '1';
so its essential i can reference the table names at a later stage, these will need piping out too.
its tricky, but ill get the hang of it!
thanks in advance. hopefully i can learn something here and apply it in future.
thanks again.
Here's my stab at it (I sure this can be done better):
{
print "tableA tableB tableC
1 1 3
2 3 2
3 2 1
tableD tableE tableF
4 4 6
5 6 5
6 3 4
" | nawk '
# New Column headings
/table/ {
# For each field (column heading)
for (i=1; i<=NF; i++) {
# Save the current column headings
current=$(i)
# Save an array pointer...
arrs[$(i)]=i
# ...and an array index
arrs_idx[$(i)]=1
}
# Move on
getline
}
# Each non column heading record
{
# For each column heading (table name)...
for (i=1; i<=NF; i++) {
# Create a record in table_array, indexed by the table name and its current index (based on current headings)
table_array[current OFS arrs_idx[current]++] = $(i)
}
}
END {
# For each table in the table array...
for (i in arrs) {
# Print its table name
print ""
print i
print "========="
# For each record in the array...
for (j=1; j<=3; j++) {
# Print the element
print table_array[i OFS j]
}
}
}
'
}
Output:
tableA
=========
1
2
3
tableB
=========
1
3
2
tableC
=========
3
2
1
tableD
=========
4
5
6
tableE
=========
4
6
3
tableF
=========
6
5
4
paste a sample output for your question....