The issue in your code,
awk 'BEGIN{min=9}{for(i=2;i<=2;i++){min=(min<$i)?min:$i}print min;exit}' file.dat
... is that you immediately exit after processing the first line of input. Your middle block there need to be triggered for every line. Then, in an END block, you can print the values that you have found. You do this in another code snippet:
awk '{if ($1 > max) max=$1}END{print max}'
Another issue is that you initialize min with a magic number (9 in the first code that I quoted, and 0 in the second piece; variables that are not explicitly initialized has the value 0 if you use them in calculations). If this magic number does not fall within the range of numbers in the actual data, then the calculated min and/or max values will be wrong. It is better to initialize both min and max to some value found in the data.
To keep track of both min and max values, you need two variables, and both of these needs to be checked against the data in the file for every line, to see whether they need updating.
As awk supports arrays, it would be natural to use arrays for min and max, with one array element per column. This is what I have done in the code below.
Generalized to any number of columns:
NF == 0 { # Skip any line that does not have data next } !initialized { # Initialize the max and min for each column from the # data on the first line of input that has data. # Then immediately skip to next line. nf = NF for (i = 1; i <= nf; ++i) max[i] = min[i] = $i initialized = 1 next } { # Loop over the columns to see if the max and/or min # values need updating. for (i = 1; i <= nf; ++i) { if (max[i] < $i) max[i] = $i if (min[i] > $i) min[i] = $i } } END { # Output max and min values for each column. for (i = 1; i <= nf; ++i) printf("Column %d: min=%s, max=%s\n", i, min[i], max[i]) }
Given this script and the data in the question:
$ awk -f script.awk file Column 1: min=0.0000, max=0.4916 Column 2: min=-24.1254, max=-23.4334
The condition NF == 0 for the first block (which is executed for all lines) is to ensure that we skip blank lines. The test means "if there are zero fields (columns) of data on this line". The variable initialized will be zero from the start (logically false), but will be set to one (logically true) as soon as the first line that has data is read.
The nf variable is initialized to NF (the number of fields) on the line that we initialize the min and max values from. This is so that the output in the END block works even if the last line has zero fields.