star
star

Reputation: 213

compare two columns using Awk

i need to compare different columns in a file and create a new column that store smallest value of all these columns e.g test.txt

label col1  col2

A 0.999966  0.618701

output

label col1  col2 smallest 
A 0.999966  0.618701 0.618701

i tried

awk '{if($3 < $2) print}' test.txt > a

awk '{if($2 < $3) print}' test.txt > b

cat a b > c

can anybody suggest anything in awk

Upvotes: 2

Views: 546

Answers (1)

Ed Morton
Ed Morton

Reputation: 204731

awk '
    NR == 1 { print $0, "smallest"; next }
    {
        min = $1
        for (i=2; i<=NF; i++) {
            if ($i < min) {
                min = $i
            }
        }
        print $0, min
    }
' test.txt

Upvotes: 1

Related Questions