
我有一個文字文件,每行都有不同的單字。
如何找到文件中最常出現的 12 行並顯示它們?
我不太擅長編寫命令腳本。
如果我可以獲得命令和解釋,以便我能夠理解如何使用它並擴展我對命令的知識,那就太好了!
答案1
您可以使用內建指令輕鬆完成此操作。
- 輸入文件的內容
sort
。我們下一步需要這個。 - 這將轉到
uniq -c
.它將計算每行的唯一出現次數。如果相似的行不相鄰,那麼如果之前沒有排序,這將無法工作。 - 然後,將其提供給另一個
sort
,後者現在以相反的順序 (r
) 並基於輸出n
的數字 ( ) 解釋進行排序uniq
。我們需要數字選項,否則數字前面的空格會導致錯誤的結果(請參閱GNUsort
的幫助了解更多)。 - 最後,僅顯示前十二行
head
。
命令將是:
sort test.txt | uniq -c | sort -rn | head -n 12
此處的輸出包含實際發生次數。
要僅獲取原始行列表,您可以將輸出透過管道傳輸到sed
:
sort test.txt | uniq -c | sort -rn | head -n 12 | sed -E 's/^ *[0-9]+ //g'
例子:
I'm not there very often
I'm not there very often
Look at me!
Look at me!
Look at me!
Hello there!
Hello there!
Hello there!
Hello there!
Hello there!
Hello there!
第一個命令的輸出,但僅選擇 2 head
:
6 Hello there!
3 Look at me!
第二個命令的輸出:
Hello there!
Look at me!