Josh Friedlander
Josh Friedlander

Reputation: 11657

Print rows where one column is the same but another is different

Given files test1 and test2:

$ cat test*
alert_name,id,severity
bar,2,1
foo,1,0
alert_name,id,severity
foo,1,9
bar,2,1

I want to find rows where name is the same but severity has changed (ie foo) and print the change. I have got this far using awk:

awk 'BEGIN{FS=","} FNR>1 && NR==FNR { a[$1]; next } ($1 in a) && ($3 != a[$3]) {printf "Alert %s severity from %s to %s\n", $1, a[$3], $3}' test1 test2

which prints:

Alert foo severity from  to 9
Alert bar severity from  to 1

So the match is wrong, and I can't print a[$3].

Upvotes: 1

Views: 44

Answers (2)

anubhava
anubhava

Reputation: 784938

You may try this awk:

awk -F, '$1 in sev && $3 != sev[$1] {
   printf "Alert %s severity from %s to %s\n", $1, sev[$1], $3
}
{sev[$1] = $3}' test*

Alert foo severity from 0 to 9

Upvotes: 3

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2817

mawk 'BEGIN { _+=(_^=FS=OFS=",")+_ } 
      FNR == NR || +$_<=+___[__=$!!_] ? !_*(___[$!!_]=$_) : \
      $!_ = "Alert "__ " severity from "___[__]" to " $_' files*.txt
Alert foo severity from 0 to 9

Upvotes: 0

Related Questions