How to Count the Number of Occurrences of a String in an Entire File

How can I count the occurrences of a string within a file?

This will output the number of lines that contain your search string.

grep -c "echo" FILE

This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).

edit:

After playing around a bit, you could get the number of occurrences using this dirty little bit of code:

sed 's/echo/echo\n/g' FILE | grep -c "echo"

This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.

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

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 

Count all occurrences of a string in lots of files with grep


cat * | grep -c string

Count the amount of times a string appears in a file

Here you are:

public int countStringInFile(String stringToLookFor, String fileName){
int count = 0;
try{
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
int startIndex = strLine.indexOf(stringToLookFor);
while (startIndex != -1) {
count++;
startIndex = base.indexOf(stringToLookFor,
startIndex +stringToLookFor.length());
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return count;
}

Usage: int count = countStringInFile("SomeWordToLookFor", "FileName");

Count the occurrences of a string in a file

Close, but a few issues:

use strict;
use warnings;

sub countModule
{
my $file = "/test";
open my $fh, "<",$file or die "could not open $file: $!";
my @contents = <$fh>; # The <> brackets are used to read from $fh.
my @filtered = grep (/\// ,@contents);
return @filtered; # Remove the reference.
}

my @lines = countModule();
my $count = scalar @lines; # 'scalar' is not required, but lends clarity.
print "###########\n $count \n###########\n";

Each of the changes I made to your code are annotated with a #comment explaining what was done.

Now in list context your subroutine will return the filtered lines. In scalar context it will return a count of how many lines were filtered.

You did also mention find the occurrences of a character (despite everything in your script being line-oriented). Perhaps your counter sub would look like this:

sub file_tallies{
my $file = '/test';
open my $fh, '<', $file or die $!;
my $count;
my $lines;
while( <$fh> ) {
$lines++;
$count += $_ =~ tr[\/][\/];
}
return ( $lines, $count );
}

my( $line_count, $slash_count ) = file_tallies();

How to count the number of occurrences of a string in a file and append it within another file

If you simply just want to tag the counter value onto the end of the file the following code should work:

import os

def main():
with open('hardDriveSummary.txt', 'ab+') as f:
term = "Product ID"
count = f.read().count(term)
f.seek(os.SEEK_END) # Because we've already read the entire file. Go to the end before writing otherwise we get an IOError
f.write('\n'+str(count))

Count number of occurrences of a pattern in a file (even on same line)

To count all occurrences, use -o. Try this:

echo afoobarfoobar | grep -o foo | wc -l

And man grep of course (:

Update

Some suggest to use just grep -co foo instead of grep -o foo | wc -l.

Don't.

This shortcut won't work in all cases. Man page says:

-c print a count of matching lines

Difference in these approaches is illustrated below:

1.

$ echo afoobarfoobar | grep -oc foo
1

As soon as the match is found in the line (a{foo}barfoobar) the searching stops. Only one line was checked and it matched, so the output is 1. Actually -o is ignored here and you could just use grep -c instead.

2.

$ echo afoobarfoobar | grep -o foo
foo
foo

$ echo afoobarfoobar | grep -o foo | wc -l
2

Two matches are found in the line (a{foo}bar{foo}bar) because we explicitly asked to find every occurrence (-o). Every occurence is printed on a separate line, and wc -l just counts the number of lines in the output.



Related Topics



Leave a reply



Submit