OXXO
OXXO

Reputation: 724

Equal values in column

I would to check if all values are the same in column 2.

If all values in column 2 are equal, the output should be

2835:  OK

If column 2 has different value , the output should be

2835:  BAD

Input file:

2835:  BAD
2835:  OK
2835:  OK
2835:  BAD
2835:  OK
2835:  BAD
2835:  OK
2835:  OK
2835:  OK

my code

awk '{a[$2]++} END { for (n in a ) print $0 " " n, a[n]}' file

Output

2835:  OK BAD 1
2835:  OK OK 35

Output desired

2835:  BAD

Thanks in advance.

Upvotes: 1

Views: 74

Answers (3)

Ed Morton
Ed Morton

Reputation: 203189

With any awk:

$ awk '!seen[$2]++{cnt++} END{print "2835:  " (cnt>1 ? "BAD" : "OK")}' file
2835:  BAD

or if the the first field of the output is related to your input values:

$ awk '{key=$1} !seen[$2]++{cnt++} END{print key "  " (cnt>1 ? "BAD" : "OK")}' file
2835:  BAD

and more efficiently:

$ awk '{key=$1} !seen[$2]++ && cnt++{exit} END{print key "  " (cnt>1 ? "BAD" : "OK")}' file
2835:  BAD

Upvotes: 1

Michael Back
Michael Back

Reputation: 1871

For one file:

awk ‘NR == 1 { a = $1; b = $2 }
     $2 != b { print a, “BAD”; exit 0 }
     END     { if (NR) print a, “OK” }’ file

For multiple files (one line output per file):

awk ‘
    function f() {
        if (ok != “”)
            print a, ok
        ok = “OK”
    }
    FNR == 1 {
        f()
        a = $1
        b = $2
    }
    $2 != b {
        ok = “BAD”
    }
    END {
        f()
    }’ file0 file1

Upvotes: 1

Cyrus
Cyrus

Reputation: 88563

With GNU grep:

grep -m 1 BAD file || grep -m 1 OK file

Upvotes: 1

Related Questions