#!/usr/bin/perl use strict; use warnings; use feature 'say'; my $last = ''; # Remember the id. my $count_1_x; my $count_nonblank; while () { my ($id, $col2, $col3) = split; if ($id ne $last) { # A new record begins. say "$last $count_1_x $count_nonblank" if $last; # Do not print at the very beginning. $last = $id; $count_1_x = $count_nonblank = 0; } $count_1_x++ if '1_x' eq $col2; $count_nonblank++ if defined $col3 and length $col3; } say "$last $count_1_x $count_nonblank" if $last; # Print for the last record. __DATA__ A 1_x 9_z A 1_x A 1_x g_z B 2_c B 1_x 1_z C 1_x 1_z C v_x 8_z D v_x s_x E 1_x F