歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 利用Linux命令行進行文本按行去重並按重復次數排序

利用Linux命令行進行文本按行去重並按重復次數排序

日期:2017/3/1 14:44:33   编辑:關於Linux
利用Linux命令行進行文本按行去重並按重復次數排序 linux命令行提供了非常強大的文本處理功能,組合利用linux命令能實現好多強大的功能。本文這裡舉例說明如何利用Linux命令行進行文本按行去重並按重復次數排序。主要用到的命令有sort,uniq和cut。其中,sort主要功能是排序,uniq主要功能是實現相鄰文本行的去重,cut可以從文本行中提取相應的文本列(簡單地說,就是按列操作文本行)。 用於演示的測試文件內容如下: [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. 實現命令及過程如下: [plain] 1、文本行去重 (1)排序 由於uniq命令只能對相鄰行進行去重復操作,所以在進行去重前,先要對文本行進行排序,使重復行集中到一起。 $ 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)去掉相鄰的重復行 $ sort test.txt | uniq Apple and Nokia. Hello World. I wanna buy an Apple device. My name is Friendfish. The Iphone of Apple company. 2、文本行去重並按重復次數排序 (1)首先,對文本行進行去重並統計重復次數(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. (2)對文本行按重復次數進行排序。 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. 1 I wanna buy an Apple device. (3)每行前面的刪除重復次數。 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. 下面附帶說一下cut命令的使用,用法如下: [plain] cut -b list [-n] [file ...] cut -c list [file ...] cut -f list [-d delim][-s][file ...] 上面的-b、-c、-f分別表示字節、字符、字段(即byte、character、field); list表示-b、-c、-f操作范圍,-n常常表示具體數字; file表示的自然是要操作的文本文件的名稱; delim(英文全寫:delimiter)表示分隔符,默認情況下為TAB; -s表示不包括那些不含分隔符的行(這樣有利於去掉注釋和標題) 三種方式中,表示從指定的范圍中提取字節(-b)、或字符(-c)、或字段(-f)。 范圍的表示方法: n 只有第n項 n- 從第n項一直到行尾 n-m 從第n項到第m項(包括m) -m 從一行的開始到第m項(包括m) - 從一行的開始到結束的所有項 在寫這篇文章的時候,用到了vim的大小寫轉化的快捷鍵:gu變小寫,gU變大寫。結合ctrl+v能夠將一片文字中的字符進行大小寫轉換,非常好用。
Copyright © Linux教程網 All Rights Reserved