linux命令行提供了非常強(qiáng)大的
文本處理功能,組合利用linux命令能實現(xiàn)好多強(qiáng)大的功能。本文這里舉例說明如何利用Linux命令行進(jìn)行文本去重并按重復(fù)次數(shù)排序。主要用到的命令有sort,uniq和cut。其中,sort主要功能是排序,uniq主要功能是實現(xiàn)相鄰文本行的去重,cut可以從文本行中提取相應(yīng)的文本列(簡單地說,就是按列操作文本行)。
利用Linux命令行進(jìn)行文本去重并按重復(fù)次數(shù)排序圖一
用于演示的測試文件內(nèi)容如下:
[plain]
Hello World.
Apple and Nokia.
Hello World.
I wanna buy an Apple device.
The Iphone of Apple company.
Hello World.
The Iphone of Apple company.
My name is Friendfish.
Hello World.
Apple and Nokia.
利用Linux命令行進(jìn)行文本去重并按重復(fù)次數(shù)排序圖二
實現(xiàn)命令及過程如下:
[plain]
1、文本行去重
(1)排序
由于uniq命令只能對相鄰行進(jìn)行去重復(fù)操作,所以在進(jìn)行去重前,先要對文本行進(jìn)行排序,使重復(fù)行集中到一起。
$ sort test.txt
Apple and Nokia.
Apple and Nokia.
Hello World.
Hello World.
Hello World.
Hello World.
I wanna buy an Apple device.
My name is Friendfish.
The Iphone of Apple company.
The Iphone of Apple company.
(2)去掉相鄰的重復(fù)行
$ sort test.txt / uniq
Apple and Nokia.
Hello World.
I wanna buy an Apple device.
My name is Friendfish.
The Iphone of Apple company.
利用Linux命令行進(jìn)行文本去重并按重復(fù)次數(shù)排序圖三
2、文本行去重并按重復(fù)次數(shù)排序
(1)首先,對文本行進(jìn)行去重并統(tǒng)計重復(fù)次數(shù)(uniq命令加-c選項可以實現(xiàn)對重復(fù)次數(shù)進(jìn)行統(tǒng)計。)。
$ 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.
(2)對文本行按重復(fù)次數(shù)進(jìn)行排序。
sort -n可以識別每行開頭的數(shù)字,并按其大小對文本行進(jìn)行排序。默認(rè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.
1 I wanna buy an Apple device.
(3)每行前面的刪除重復(fù)次數(shù)。
cut命令可以按列操作文本行�?梢钥闯銮懊娴闹貜�(fù)次數(shù)占8個字符,因此,可以用命令cut -c 9- 取出每行第9個及其以后的字符。
$ sort test.txt / uniq -c / sort -rn / cut -c 9-
Hello World.
The Iphone of Apple company.
12下一頁>