Say I have the following data:

cat file
0.000   0.0 425.2   2.23
0.000   0.0 477.9   0.91
0.000   0.0 516.5   -0.41
0.000   0.0 566.5   -3.72

Within my awk script regress.awk, I would like to set a variable temp equal to the third field on the first line, so temp = 425.2. Is there a simple way in awk to accomplish this? I can't figure out how to combine NF and NR. From the prompt I can use:

awk 'NR==1 {print $3}' file

Which will return 425.2, but I have no clue how to store that as a variable within an awk script. It seems like setting variables equal to a column is easy, but haven't ever seen anything about associating a specific row with them.

1 Answer 1

awk '{NR==1 { temp=$3 } NR>1 { /* do stuff that refers to temp */ }' /path/to/file
  • You are the man, I could have swore I tried that solution, but I guess I messed up the syntax somewhere. Out of curiosity, what is the purpose of NR>1, it seems like after setting 'temp' you can proceed? Thanks for your help and time, much appreciated.
    – Henry
    Commented Feb 22, 2017 at 22:42
  • 1
    The reasoning behind that is to make is such that temp is only referred to after it's been defined. You could try not using the NR>1 restriction, but you might get an error or warning about using an undefined variable on the first record. If I had to hazard a guess as to why your first try didn't work, you might have done what I did the first time I tested this, and tried to use NR=1 rather than NR==1 (:
    – DopeGhoti
    Commented Feb 22, 2017 at 22:52
  • Pleased to have been of assistance.
    – DopeGhoti
    Commented Feb 22, 2017 at 23:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .