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

前端 未结 6 857
夕颜
夕颜 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:22

    This loops over the lines of the file, and on each line finds all occurrences of the string "(*)". Each time that string is found, $c is incremented. When there are no more lines to loop over, the value of $c is printed.

    perl -ne'$c++ while /\(\*\)/g;END{print"$c\n"}' filename.txt

    Update: Regarding your comment asking that this be converted into a solution that accepts a regex as an argument, you might do it like this:

    perl -ne'BEGIN{$re=shift;}$c++ while /\Q$re/g;END{print"$c\n"}' 'regex' filename.txt

    That ought to do the trick. If I felt inclined to skim through perlrun again I might see a more elegant solution, but this should work.

    You could also eliminate the explicit inner while loop in favor of an implicit one by providing list context to the regexp:

    perl -ne'BEGIN{$re=shift}$c+=()=/\Q$re/g;END{print"$c\n"}' 'regex' filename.txt

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-12-21 02:23
    text="(\*)"
    grep -o $text file | wc -l
    

    You can make it into a script which accepts arguments like this:

    script count:

    #!/bin/bash
    text="$1"
    file="$2"
    grep -o "$text" "$file" | wc -l
    

    Usage:

    ./count "(\*)" file_path
    
    0 讨论(0)
  • 2020-12-21 02:30

    You can use basic grep command:

    Example: If you want to find the no of occurrence of "hello" word in a file

    grep -c "hello" filename
    

    If you want to find the no of occurrence of a pattern then

    grep -c -P "Your Pattern"
    

    Pattern example : hell.w, \d+ etc

    0 讨论(0)
  • 2020-12-21 02:45

    You can use basic tools such as grep and wc:

    grep -o '(\*)' input.txt | wc -l
    
    0 讨论(0)
  • 2020-12-21 02:47

    I have used below command to find particular string count in a file

    grep search_String fileName|wc -l

    0 讨论(0)
提交回复
热议问题