0

Hi i have a file like this (with n-lines):

0.001  5.4e+08 
0.03  0.08
0.5774  0.1
93  9832

now i want to read the maximum value of each column. i tried awk like this:

awk -v "max=0.2" -v "index=1" 'BEGIN{if (index>max) max=index} END {print max}' file

and asign the output to a variable. Only typing the awk command in the shell gives me this error:

awk: run time error: cannot command line assign to index
    type clash or keyword
    FILENAME="" FNR=0 NR=0

The Problem is that the file has n-lines and i am only looping over certain lines. How can i give awk the line to work on and read out the maximum value of the column of that line?

3
  • it does, the solution was that i shouldnt use "index" as a variable name
    – Tuni
    Dec 18, 2016 at 17:07
  • 1
    You should mention this specific constraint as part of the question, without it, the problem is an exact duplicate.
    – Inian
    Dec 18, 2016 at 17:08
  • Aside from the syntax issues, this was literally the last question I answered, over here.
    – ghoti
    Dec 18, 2016 at 17:19

1 Answer 1

5

index() is the name of an awk function, pick a different variable name like idx.

Also, to print the max value of an "index" you don't need to seed the max with some ad-hoc value, it would just be:

$ awk -v idx=1 'NR==1 || $idx>max{max=$idx} END{print max}' file
93
5
  • okay but if i do: awk -v "max=0.001" -v "idx=1" 'BEGIN{if ($idx>max) max=$idx} END {print max}' CH4_p01a00242tf0300to0300.kg my output is:0.001 whilst it should be 93
    – Tuni
    Dec 18, 2016 at 17:06
  • 1
    Well, yeah, you've stuck your computation in a BEGIN section which is executed before your input file is opened so what you get in the END is what you had before you started.
    – Ed Morton
    Dec 18, 2016 at 17:07
  • 1
    now i know what to use BEGIN and END for, thank you for the help!
    – Tuni
    Dec 18, 2016 at 17:15
  • @EdMorton - also, you don't need to set max on NR==1 either, as long as $1 will be positive. An uninitialized variable evaluates as zero. awk 'BEGIN{if(1>a)print"foo";if(a>1)print"bar"}' returns only foo.
    – ghoti
    Dec 18, 2016 at 17:27
  • @ghoti When doing min/max calculations you should always init using the first value read rather than some ad-hoc value you assume/hope will be less/more than the max/min in the data. It's much more robust and has close to zero overhead in code or performance. Uninitialized variables have the value zero-or-null, btw, since their type is numeric-string, assuming it'll be zero (or null) can cause problems.
    – Ed Morton
    Dec 18, 2016 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.