-3

For example:

  • RXOTG-1388 holds 3 object RM4FD1,RM4FD2,RM4FD3
  • RXOTG-1398 holds 3 object VT08D1 VT08D2,VT08D3
  • and so on.

Based on this text file I would like to count, using awk, how many object each RXOTG holds.

RXOTG-1388       RM4FD1               0
                 RM4FD2               0
                 RM4FD3               0

END
RXOTG-1398       VT08D1               0
                 VT08D2               0
                 VT08D3               0

END
RXOTG-1400       VT08S1               0
                 VT08S2               0
                 VT08S3               0

END
0
awk '
    /^RXOTG/{
        if(count)
            print count
        printf "%s\t", $1
        count = 0
    }
    /.{6,}/{
        count++
    }
    END{
        print count
    }'
0
awk '/^RXOTG/{x=$1; y=0}/^RXOTG/,/^$/{y++}/^END/{print x": "y-1}' in
  • /^RXOTG/{x=$1; y=0}: if the current record starts with RXOTG, assigns the value of the first field to x and 0 to y;
  • /^RXOTG/,/^$/{y++}: if the current record is in a range between a record starting with RXOTG and an empty record, increases y;
  • /^END/{print x": "y-1}: if the current record starts with END, prints the value of x followed by : followed by the value of y decreased by 1.
% cat in
RXOTG-1388       RM4FD1               0
                 RM4FD2               0
                 RM4FD3               0

END
RXOTG-1398       VT08D1               0
                 VT08D2               0
                 VT08D3               0

END
RXOTG-1400       VT08S1               0
                 VT08S2               0
                 VT08S3               0

END
% awk '/^RXOTG/{x=$1; y=0}/^RXOTG/,/^$/{y++}/^END/{print x": "y-1}' in
RXOTG-1388: 3
RXOTG-1398: 3
RXOTG-1400: 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.