Wednesday, September 28, 2022
HomeTechnologyHow to Count All Matches of a String Using Linux's grep

How to Count All Matches of a String Using Linux’s grep

- Advertisement -

grep is a text search utility that can process standard input or multiple files simultaneously. It is used to print the matches of a pattern, string or regular expression.It is often useful to be able to count the number of matches, which grep Can be done easily.

Count matches with grep

This grep The command has -c banner, it will count the number of matching lines and print out a number. This is useful for many things, such as searching log files for the number of entries from particle IPs, endpoints, or other identifiers.

grep -c "" /var/log/nginx/access.log

However, grep Each line can be matched multiple times.if you use -o banner, grep A new line is printed out for each match.This does not apply to -c flag as it will only count matches lineinstead of multiple matches per line.

A better solution is to use wc (Word Count) Utility -l (row) parameter, This will count the number of raw lines passed to it via standard input.use wc -l is the preferred solution as it works for -o Counts the number of times a given string or pattern occurs throughout the file.

grep -o "foo" file | wc -l

Count across multiple files

a nice feature grep is the ability to process multiple files at once, either through xargs, parameter, or provide wildcard expansion. When working with multiple files, grep will print out the filename before matching.when using it -c To count the number of matching lines, it also prints out the filename:

grep "foo" ./*.txt -cH

you should always use -H Flag when handling the possibility of multiple files, because it will always print the filename even if only one file is passed to it grep. This will prevent the automation from breaking if you rely on the filename there.

if you want to use -o Count multiple matches per line, and pass the output to wc -lunfortunately you will be able to see the numbers for each individual file, e.g. -c. However, with some scripting, you can cut off the first column cutand count the number of unique occurrences of each filename uniq -c:

grep "foo" ./*.txt -o | cut -d ':' -f 1 | uniq -c

related: How to Extract and Sort Columns from Log Files on Linux



Latest News