Shell Tricks: list files with most text matches

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: