3

My file looks like this:

id12 ack dko hhhh chfl dkl dll chfl
id14 slo ksol chfl dloo
id13 mse
id23 clos chfl dll alo

grep -c 'chfl' filename, gives me the number of occurrence of chfl, but I want to count occurrence of chfl per line. Like this:

id12 2
id14 1
id13 0
id23 1

Also how do I do the same with two patterns to match? Like chfl and dll?

2
  • That will also match partially, if you have a string achflop for instance. Is that what you want?
    – TLP
    Mar 17, 2014 at 12:48
  • Also, if you have two (or more) search patterns, do you want a sum total count, or one for each word?
    – TLP
    Mar 17, 2014 at 12:54

8 Answers 8

2
perl -lane 'undef $c;
            for(@F){$c++ if(/^chfl$/)};
            print "$F[0] ",$c?$c:"0"' your_file

Or simply:

perl -lane '$c=0;
            for(@F){$c++ if(/^chfl$/)};
            print "$F[0] $c"' your_file

Tested below:

> cat temp
id12 ack dko hhhh chfl dkl dll chfl
id14 slo ksol chfl dloo
id13 mse
id23 clos chfl dll alo
> perl -lane '$c=0;for(@F){$c++ if(/^chfl$/)};print "$F[0] $c"' temp
id12 2
id14 1
id13 0
id23 1
> 

Also in awk:(Logic here remains the same as above one in perl)

awk '{a=0;
     for(i=1;i<=NF;i++)if($i~/chfl/)a++;
     print $1,a}' your_file
4
  • -a says split the line into an array @F with each word as an array element.Now count all the words which match with chfl in the current array. initialize the counter for every line with 0.then print the first element in the array and the counter value.
    – Vijay
    Mar 17, 2014 at 14:18
  • then what do other values do ? l ,n, e and does @F doesnt need a declaration like $c ?
    – aelor
    Mar 17, 2014 at 14:22
  • Why dont you google them: turtle.ee.ncku.edu.tw/docs/perl/programming/pl-opt.html
    – Vijay
    Mar 17, 2014 at 14:23
  • No @F doesnot need a declaration. Its an implicitly created array.
    – Vijay
    Mar 17, 2014 at 14:24
2

A Perl version that copes with multiple strings.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

die "Usage: $0 pattern [pattern ...] file\n" unless @ARGV > 1;

my @patterns;
until (@ARGV == 1) {
  push @patterns, shift;
}

my $re = '(' . join('|', map { "\Q$_\E" } @patterns) . ')';

my %match;
while (<>) {
  if (my @matches = /$re/g) {
    $match{$_}++ for @matches;
  }
}

say "$_: $match{$_}" for sort keys %match;

A couple of test runs:

$ ./cgrep chfl dll cgrep.txt 
chfl: 4
$ ./cgrep chfl dll cgrep.txt 
chfl: 4
dll: 2
1

How about:

my %res;
while(<DATA>) {
    chomp;
    my ($id,$rest) = $_ =~ /^(\S+)(.*)$/;
    $res{chfl}{$id} =()= $rest =~ /(chfl)/g;
    $res{dll}{$id} =()= $rest =~ /(dll)/g;
}
say Dumper\%res;

__DATA__
id12 ack dko hhhh chfl dkl dll chfl
id14 slo ksol chfl dloo
id13 mse
id23 clos chfl dll alo

output:

$VAR1 = {
          'dll' => {
                     'id13' => 0,
                     'id12' => 1,
                     'id23' => 1,
                     'id14' => 0
                   },
          'chfl' => {
                      'id13' => 0,
                      'id12' => 2,
                      'id23' => 1,
                      'id14' => 1
                    }
        };
1
  • 2
    Using a hash will nuke the order of the lines, though. And it will not work if the ids are not unique.
    – TLP
    Mar 17, 2014 at 12:51
1

Use this:

awk 'BEGIN {print "id\tchfl\tdll\n--------------------"}{c=d=i=0;while(i++<NF){if($i=="chfl")c++; if($i=="dll")d++}; print $1,c,d}' OFS="\t" file
id      chfl    dll
--------------------
id12    2       1
id14    1       0
id13    0       0
id23    1       1
2
  • my patters are actually like clfl|4blabla and dll|xyzabc. This solution is not able to show the exact count Mar 17, 2014 at 13:10
  • 1
    @user3428782 Then update your post to show the data you need solution for. This solution works fine for above data.
    – Jotne
    Mar 17, 2014 at 13:23
1

Another version of awk:

$ awk '{c1=gsub(var1,x);c2=gsub(var2,x);print $1,var1"="c1,var2"="c2}' var1="chfl" var2="dll"  file
id12 chfl=2 dll=1
id14 chfl=1 dll=0
id13 chfl=0 dll=0
id23 chfl=1 dll=1

Just pass the variables you want to count at the end of the file.

1

bash one liner with grep:

while read line ; do echo $line | grep -o 'chfl' | wc -l  ; done < your_file

-o outputs every occurence on a new line and wc counts them.

Edit for multiple patterns:

patterns=(chfl dll)

while read line ; do
    for pattern in ${patterns[@]} ; do
        echo -ne $pattern"\t" ; echo $line | grep -o $pattern | wc -l 
    done
done < your_file
0

You can use this awk,

awk '{d=c=0;for(i=1;i<=NF;i++){ if($i ~ /chfl/)c++; if($i ~ /dll/)d++;} print $1,c,d}' yourfile
0
perl -ne 'my $c=s/chfl//g||0;my $d=s/dll//g||0;s/ .*//s;print "$_ chfl $c dll $d\n"' file

Explanation:

  • s///g in scalar context returns the number of substitutions made
  • ||0 make sure the variable is set to zero if there are no matches
  • s/ .*//s throws away everything from the 1st space from $_, leaving the id only

It will produce the following output:

id12 chfl 2 dll 1
id14 chfl 1 dll 0
id13 chfl 0 dll 0    
id23 chfl 1 dll 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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