Hamed Ghadimi
Hamed Ghadimi

Reputation: 29

How to merge some lines in awk?

I want to merge some rows in this file.

file.txt looks like this:

Adr R/W cnt
123 R   6
123 W   5
124 R   7
125 W   8
130 W   11
130 R   12

I would like it to look like this:

Adr W   R
123 5   6
124 0   7
125 8   0
130 11  12

I have tried this so far:

awk '{a=$1; b=$2; c=$3; getline; d=$1; e=$2; f=$3;
    if(a==d && b=="W")
        print a " " c " " f;
    else if(a==d && b=="R")
        print a " " f " " c;
    else if (a!=d && b=="W")
        print a " " c " 0";
    else if(a!=d && b=="R")
        print a " 0 " c;}' file.txt

Upvotes: 3

Views: 59

Answers (1)

glenn jackman
glenn jackman

Reputation: 247250

This uses GNU awk's array of arrays feature:

gawk '
  NR>1 {val[$1][$2] = $3} 
  END {
    print "Adr W R"
    for (id in val) print id, 0 + val[id]["W"], 0 + val[id]["R"]
  }
' file.txt | column -t
Adr  W   R
123  5   6
124  0   7
125  8   0
130  11  12

Adding zero to an undefined value returns the number zero.

Upvotes: 2

Related Questions