How to Calculate the Minimum and Maximum of a Column in awk on Linux

When you are executing a massive statistical audit on a system log within a Linux terminal, you frequently need to identify the absolute boundaries of the dataset (e.g., finding the single highest CPU temperature or the lowest ping latency). The awk language architecture does not possess native min() or max() subroutines. To force the engine to independently calculate the geometric minimum and maximum of a specific data column, you must deploy an aggressive comparative logic loop.

Executing the Boundary Matrix

To calculate the Max, you must instruct the engine to hold a max_val variable in RAM. As it iterates through the file, it constantly compares the current row’s data against the stored max_val. If the new data is mathematically higher, it violently overwrites the max_val. To calculate the Min, the logic is identical, but inverted.

Deploying the Comparative Vector

Imagine you have a file named sensor_data.txt. Column 2 contains the raw temperature reading in Celsius (e.g., 45, 99, 12, 105, 30). You must output the absolute lowest and highest temperatures recorded in the entire dataset.

To execute the statistical extraction vector, analyze this precise command:

awk 'NR == 1 { min_val = $2; max_val = $2 } { if ($2 < min_val) min_val = $2; if ($2 > max_val) max_val = $2 } END { print "Absolute Minimum:", min_val, "| Absolute Maximum:", max_val }' sensor_data.txt

Analyzing the Comparative Calculus

The exact millisecond you execute this script, the awk engine intercepts the payload.

  • The engine reads the absolute first row (e.g., temperature is 45).
  • The NR == 1 block triggers. This is the initialization protocol. The engine must seed the min_val and max_val variables with the very first number it sees (45) to establish a baseline for comparison. If you initialize them at 0, the Min logic will catastrophically fail on datasets that never drop below 0.
  • The engine reads the second row (e.g., 99).
  • It hits the comparative logic gate: if ($2 < min_val). 99 is not less than 45. The gate ignores it.
  • It hits the second gate: if ($2 > max_val). 99 is greater than 45. The gate triggers and violently overwrites max_val with 99.
  • The engine iterates through the entire multi-gigabyte log file. If it encounters a 12, it overwrites min_val. If it encounters a 105, it overwrites max_val.
  • Once absolute EOF (End of File) is reached, the END block triggers, dumping the pristine, locked statistical boundaries (12 and 105) to the terminal screen.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.