How do I count the number of occurrences of a string in an entire file?

前端 未结 6 886
夕颜
夕颜 2020-12-21 02:17

Is there an inbuilt command to do this or has anyone had any luck with a script that does it?

I am looking to count the number of times a certain string (not word) a

6条回答
  •  情深已故
    2020-12-21 02:23

    Using perl's "Eskimo kiss" operator with the -n switch to print a total at the end. Use \Q...\E to ignore any meta characters.

    perl -lnwe '$a+=()=/\Q(*)/g; }{ print $a;' file.txt
    

    Script:

    use strict;
    use warnings;
    
    my $count;
    my $text = shift;
    
    while (<>) {
        $count += () = /\Q$text/g;
    }
    
    print "$count\n";
    

    Usage:

    perl script.pl "(*)" file.txt 
    

提交回复
热议问题