Kay
Kay

Reputation: 2067

Find minimum value using awk

I am trying to find the minimum value from a file.

input.txt
1
2
4
5
6
4

This is the code that I am using:

awk '{sum += $1; min = min < $1 ? min : $1} !(FNR%6){print min;sum=min = ""}' input.txt

But it is not working. Can anybody see the error in my code?

Upvotes: 0

Views: 2470

Answers (2)

Kasun Rathnayaka
Kasun Rathnayaka

Reputation: 503

use below scrip to find min value in txt file.

  awk 'min=="" || $1 < min {min=$1} END {print min}' input.txt

Upvotes: 4

samgak
samgak

Reputation: 24417

Set min to $1 on the first line

awk 'NR == 1 {min = $1} {sum += $1; min = min < $1 ? min : $1} !(FNR%6){print min;sum=min = ""}' input.txt

output:

1

Note that sum isn't used, you could simplify to this:

awk 'NR == 1 {min = $1;} {min = min < $1 ? min : $1} !(FNR%6){print min;}' input.txt

To allow any number of lines:

awk 'NR == 1 {min = $1;} {min = min < $1 ? min : $1} END{print min;}' input.txt

Upvotes: 3

Related Questions