function traverse(k, j) { ## NOTE that consistent recursion requires input files to be sorted by "site" (column 9) printf("%s,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", GID[k], order++, res[k], resID[k], name[k], anomer[k], absolute[k], ring[k], parentID[k], site[k], pubChem[k]); for (j = 1; j <= length(GID); j++) { if (parentID[j] == resID[k]) { traverse(j); ## RECURSION! } } } BEGIN { FS = ","; exist = 0; ## specifies that arrays do NOT exist initially } NR == 1 { ## reading first line of first file ## print out header only from first file, adding an order column that corresponds to depth-first traversal printf("%s,order,%s,%s,%s,%s,%s,%s,%s,%s,%s\n",$1,$2,$3,$4,$5,$6,$7,$8,$9,$12); } FNR == 2 { ## reading second line of this file ## for last structure, do a depth-first traversal order = 1; ## find root residue (parent has "no_id") and start traversal there for (q = 1; q < length(GID); q++) { if ( (parentID[q] == "no_id") && (exist == 1) ) { ## printf("(inside) traversing %s residue %d: %s\n", GID[q], q, resID[q]); traverse(q); } } exist = 1; ## specifies that arrays DO exist from here on ## then delete all the arrays for LAST structure so they can be repopulated delete GID; delete res; delete resID; delete name; delete anomer; delete absolute; delete ring; delete parentID; delete site; delete pubChem; ## reset i at line 2 of each file i = 0; } FNR > 1 { ## reading second to nth line of this file i++; ## increment the array index # this block reads the parts csv file and puts the properties of each part residue in arrays GID[i] = $1; res[i] = $2; resID[i] = $3; name[i] = $4; anomer[i] = $5; absolute[i] = $6; ring[i] = $7; parentID[i] = $8; site[i] = $9; pubChem[i] = $12; } END { ## traverse from root of LAST file order = 1; for (q = 1; q < length(GID); q++) { if ( (parentID[q] == "no_id") && (exist == 1) ) { ## printf("(END) traversing %s residue %d: %s\n", GID[q], q, resID[q]); traverse(q); } } }