next up previous 405
Next: Reading from dynamic text files
Up: Reading tabular data
Previous: Selecting a range

Choosing columns by name

Suppose your text file has a heading line listing the names of the columns.

    set name = Vmag
    set cn = `awk -v col=$name '{if (NR==1) {for(i=1;i<=NF;\
              i++) {if ($i==col) {print i; break}}}}' fornax.dat`
That looks complicated, so let's go through it step by step. We supply the required column name name into the awk variable col through to -v command-line option. For the first record NR==1, we loop through all the fields (NF starting at the first, and if the current column name ($i) equals the requested name, the column number is printed and we break from the loop. If the field is not present, the result is null. The extra braces associate commands in the same for or if block. Note that unlike C-shell, in awk the line break can only appear immediately after a semicolon or brace.

The above can be improved upon using the toupper function to avoid case sensitivity.

    set name = Vmag
    set cn = `awk -v col=$name '{if (NR==1) {for(i=1;i<=NF;\
              i++) {if (toupper($i)==toupper(col)) {print i; break}}}}' fornax.dat`
Or you could attempt to match a regular expression.

next up previous 405
Next: Reading from dynamic text files
Up: Reading tabular data
Previous: Selecting a range

C-shell Cookbook
Starlink Cookbook 4
Malcolm J. Currie
2006 November 26
E-mail:ussc@star.rl.ac.uk

Copyright © 2009 Science and Technology Facilities Council