Here’s a Bash function for searching all text files in the current directory for a pattern, then listing the files containing matches in ascending order by number of matches. It’s mostly a proof of concept, but a useful companion to a basic grep search.
The meat of the script happens in an array declaration. It first uses grep -lIi -E "$patt" * 2> /dev/null to list files containing the provided pattern (case insensitive), ignoring binary files. The error redirect at the end of the command will ignore the errors thrown by directories. The results of this are fed to another grep command: grep -Hi -c -E "$patt" which outputs the match count for each file. The results are saved to the array.
After including the function in a sourced file (e.g. ~/.bash_profile), running matches -h will show the available flags and switches:
$ matches -h
Find files in the current directory containing the most occurrences
of a pattern
-c Include occurrence counts in output
-r Reverse sort order (default ascending)
-m COUNT Minimum number of matches required
-h Display this help screen
# search for files containing at least 3 occurrences
# of the word "jekyll", display filenames with counts
$ matches -c -m 3 jekyll
Here’s the function for pasting into ~/.bash_profile (or other sourced file):
Ryan Irelan has produced a series of shell trick videos based on BrettTerpstra.com posts. Readers can get 10% off using the coupon code TERPSTRA.