Shell-Script
如何打開與給定正則表達式匹配最多的文件?
假設我有一個目錄
~/mydir
,裡面有一大堆文本文件。我想在這個目錄中搜尋searchterm
,然後查看匹配最多的文件。我怎樣才能只使用一個命令來做到這一點?
將以下行放入腳本中即可:
grep -c "$1" ~/mydir/* | grep -v ':0' | sort -t: -k2 -r -n | head -1 | sed 's/:.*//' | xargs less
然後打電話
./myscript searchterm
如果要遞歸搜尋,請在第一個命令中更改
-c
為。-cr``grep
此管道的各個部分,按順序:
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 將打開空。