linux命令行提供了非常強大的文本處理功能,組合利用linux命令能實現好多強大的功能。本文這里舉例說明如何利用linux命令行進行文本按行去重并按重復次數排序。主要用到的命令有sort,uniq和cut。其中,sort主要功能是排序,uniq主要功能是實現相鄰文本行的去重,cut可以從文本行中提取相應的文本列(簡單地說,就是按列操作文本行)。
文本行去重并按重復次數排序?
例:
首先,對文本行進行去重并統計重復次數(uniq命令加-c選項可以實現對重復次數進行統計)。?
$ sort test.txt | uniq -c 2 Apple and Nokia. 4 Hello World. 1 I wanna buy an Apple device. 1 My name is Friendfish. 2 The Iphone of Apple company.
對文本行按重復次數進行排序。?
sort?-n可以識別每行開頭的數字,并按其大小對文本行進行排序。默認是按升序排列,如果想要按降序要加-r選項(sort?-rn)。?
$ sort test.txt | uniq -c | sort -rn 4 Hello World. 2 The Iphone of Apple company. 2 Apple and Nokia. 1 My name is Friendfish.
每行前面的刪除重復次數。?
cut命令可以按列操作文本行。可以看出前面的重復次數占8個字符,因此,可以用命令cut -c 9- 取出每行第9個及其以后的字符。
$ sort test.txt | uniq -c | sort -rn | cut -c 9- Hello World. The Iphone of Apple company. Apple and Nokia. My name is Friendfish. I wanna buy an Apple device.
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END