Colocar a seguinte linha em um script fará isso:
grep -c "$1" ~/mydir/* | grep -v ':0' | sort -t: -k2 -r -n | head -1 | sed 's/:.*//' | xargs less
Depois é só ligar para ./myscript searchterm
Se você quiser pesquisar recursivamente, altere -c
para -cr
no primeiro comando grep
.
As partes deste pipeline, na ordem:
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 field
head -1 # Extracts only the first result
# (the most matches)
sed 's/:.*//' # Removes the trailing ':<count>' as we're
# done with it
xargs less # Passes the resulting filename as
# an argument to less
Se não houver correspondência, menos será aberto vazio.