How to find a minimum value of a row?

input

1 2 3 4 5 2 8
2 1 1 1 4 2 1
5 4 4 4 2 1 3
2 2 6 7 4 5 4
5 5 5 4 3 3 5
 

I woud like to print a min of each row such that my output would look like

1
1
1
2
3

Thanks!

awk 'BEGIN{min=9}{for(i=1;i<=NF;i++){min=(min<$i)?min:$i}print min;min=9}' file
1 Like

I also found that this works as well

awk '{for (i=1;i<=NF;i++) {$1=($i<$1)?$i:$1} print $1}' file.txt
1 Like

In my opinion, you both are trying to be too clever. Throw away the unnecessary hardcoded maximum (9 in post #2) and the pointless ternary operators in favor of more readable code:

awk '{m=$1; for (i=2; i<=NF; i++) if ($i < m) m = $i; print m}' file.txt

Regards,
Alister

1 Like

This is much easy to read! Thanks :slight_smile:

Aside from readability, that ternary approach is also inefficient. It requires an assignment to be made even when one is not needed. Further, assigning to a field triggers recomputing and rebuilding of $0.

Regards,
Alister