標籤:
轉自:http://blog.csdn.net/wklken/article/details/6562098
Sort,uniq,join,cut,paste,split
命令—— Sort
Sort 可將許多不同的域按不同的列順序分類
命令格式:
sort –cmu –o out-putfile [other options] *pos1 *pos2 input-files
選項:
-c 測試檔案是否已經分類
-m 合并兩個分類檔案
-u 刪除所有複製行
-o 儲存 sort 結果的輸出檔案名
-b 使用域進行分類是,忽略首個空格
-n 指定分類是域上數字分類
-t 域分隔字元;用非空個或者 tab 鍵分割域
-r 對分類次序或比較求逆
+n n 為域號,使用此域開始分類
n n 為域號,在分類比較時忽略此域,一般與 +n 一起使用
post m,n 傳遞到 m,n , m 為域號, n 為開始分類字元數
樣本 :
1. 儲存輸出
$sort –o result sortfile
$sort sortfile > result
Sort 的啟動方式, sort 認為一空格 / 多空格為分隔字元,要加入其他的,必須使用 -t ,執行時,先查看 -t, 若是有,使用其進行分割,若是無,使用空格
2. 查看檔案是否已排序
$sort –c sortfile
3. 使用其他分隔字元
$sort –t : sortfile
4. 排完序後求逆
$sort –t : -r sortfile
5. 唯一分類,原檔案中重複行去除
$sort –u sortfile
6. 指定分類域, 1 開始
$sort –t : -k 4 sortfile
$sort –t : -k 4 –k 1 sortfile
7. 指定 sort 序列
$sort +0 -2 +3 sortfile
8. 將兩個分類檔案合并
$sort –m sorted-file1 sorted_file2
命令—— uniq
Uniq 從文字檔中去除或禁止重複行,一般 uniq 假定檔案已分類排序,並且結果正確 [sort –u 唯一性選項去除所有的重複行 ]
Uniq 中重複行指持續不斷重複出現的行
格式 :uniq –udc –f input-file output-file
選項:
-u 只顯示不重複行
-d 只顯示有重複的行,每種重複顯示一行
-c 列印每一重複行出現的次數
-f n 為數字,前 n 個域被忽略
1. 只顯示非重複行
$uniq –u sortfile
2. 提取非重複行到某個檔案
$uniq –u sortfile result
3. 只顯示重複行
$uniq –d sortfile
4. 列印重複行及其出現的次數
$uniq –c sortfile
5. 忽略比較指定列
$uniq –f2 parts.txt
命令—— join
將來自兩個分類文字檔的行連在一起
前提 : file1,file2 已分類
每個檔案都有一些元素與另一檔案相關——連
有點像求並集
註: joio 時文本域要少於 20=
格式: join [options] input-file input-file2
選項:
an n 為數字,用於串連時從檔案 n 中顯示不匹配行 ,-a1 表示第一個檔案的不匹配行
o n,m n 為檔案號, m 為域號, 1,3 表示只顯示檔案 1 的第三域
j n m n 為檔案號, m 為域 使用其他域做串連域
t 域分隔字元 用來設定非空格 / 非 tab 分隔字元
1. 串連兩個檔案 [ 預設串連域為域 0]
$Join name.txt. turn.txt
2. 顯示第一個檔案的不匹配行
$join –a1 name.txt town.txt
3. 設定顯示串連結果
$join –o 1.1,2.2 name.txt town.txt
第一個檔案第一個域和第二個檔案第二個域作為顯示結果
4. 設定串連域
$join –j 1 3 –j 2 2 file1 file2
命令—— cut
用來從標準輸入或文字檔中剪下列或域
可將剪下到的文本貼到另一個檔案中
格式 :cut [options] file1 file2
選項:
-c list 指定剪下字元數
-f field 指定剪下域數
-d 指定與空格 /tab 不同的分隔字元
-c 指定剪下的字元範圍,字元,如 -c 1,5,7 第 1,5,6,7 字元 -c 1-50 前 50 個字元
-f 指定剪下的域範圍 -f 1,5 剪下 1,5 兩個域 -f 1,10-12 剪下 1,10,11,12 四個域
1. 使用域分隔字元
$cut –d : -f3 data
[[email protected] temp]# cut -d: -f1 /etc/passwd |head -5
root
bin
daemon
adm
lp
–d : 指示cut改用:為分隔字元,-f1表示第一個欄位意思。
2. 剪下指定域
$cut –d: -f1,3 data ##表示取出各行第一及第三個欄位意思
3. 剪下字元
$who –u| cut –c 1-8
[[email protected] temp]# who -u
root tty1 2011-10-19 22:09 old 2463 (:0)
root pts/0 2011-11-0408:48 . 7804(192.168.0.86)
root pts/2 2011-10-3109:25 old 18934(:0.0)
root pts/3 2011-10-3109:47 old 18934(:0.0)
[[email protected] temp]# who -u |cut -c 1-8
root
root
root
root
命令: paste
Paste 將資料貼到相關檔案中
存在兩個不同來源 資料應先分類,確保檔案行數同
格式 :paste –d –s file1file2
選項:
-d 指定不同分隔字元
-s 將每個檔案合并成行而不是按行黏貼
File1
1
2
File2
A
B
1. 合并之
$pastefile1 file2
1 A
2 B
2. 指定分隔字元
$paste–d: file2 file1
A:1
B:2
3. 合并兩行,而非按行黏貼
$paste–s file1 file2
命令: split
用來將檔案切分為小檔案
格式: split–output_file_size input_filename output_filename
其中 out_file_size 為被分割行數,預設 1000
轉-Shell筆記——命令:Sort,uniq,join,cut,paste,split