Let's say I have a directory ~/mydir that has a whole bunch of text files in it.  I want to search for searchterm in this directory and then view the file that has the most matches.  How can I do this using only one command?
How can I open the file with the most matches for a given regex?
shell script;command line;grep;pipe
Putting the following line in a script will do it:grep -c $1 ~/mydir/* | grep -v ':0' | sort -t: -k2 -r -n | head -1 | sed 's/:.*//' | xargs lessThen just call ./myscript searchtermIf you want to search recursively, change -c to -cr in the first grep command.The parts of this pipeline, in order:grep -c $1 ~/mydir/*    # Outputs a list of the files in ~/mydir/ with :<count>                          # appended to each, where <count> is the number of                          # matches of the $1 pattern in the file.grep -v ':0'              # Removes the files that have 0 results from                          # the list.sort -t: -k2 -r -n        # Sorts the list in reverse numerical order                          # (highest numbers first) based on the                          # second ':'-delimited fieldhead -1                   # Extracts only the first result                          # (the most matches)sed 's/:.*//'             # Removes the trailing ':<count>' as we're                          # done with itxargs less                # Passes the resulting filename as                          # an argument to lessIf there is no match at all, less will open empty.