從 Linux 中的檔案中取得最常見的行

從 Linux 中的檔案中取得最常見的行

我有一個文字文件,每行都有不同的單字。
如何找到文件中最常出現的 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!

答案2

如果你的發行版有日誌頂部

cat your_file | logtop

如果您的文件不斷增長(例如日誌文件),請嘗試:

tail -f your_log | logtop

相關內容