如何打开给定正则表达式最匹配的文件?

如何打开给定正则表达式最匹配的文件?

假设我有一个目录~/mydir,其中包含一大堆文本文件。我想在这个目录中搜索searchterm,然后查看匹配最多的文件。如何仅使用一个命令来完成此操作?

答案1

将以下行放入脚本中即可完成:

grep -c "$1" ~/mydir/* | grep -v ':0' | sort -t: -k2 -r -n | head -1 | sed 's/:.*//' | xargs less

然后只需调用./myscript searchterm

如果要递归搜索,请在第一个命令中更改-c为。-crgrep

该管道的各个部分(按顺序):

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

如果根本没有匹配项,则 less 将打开空。

答案2

就够了

grep -c 'pattern' ~/mydir/* 2>/dev/null| sort -rk2n -t:| sed 's/:.*//;q'

相关内容