linux文本處理 sort,grep,sed,awk,uniq 用法
來自: http://blog.csdn.net//wgw335363240/article/details/45720537
一、sort
Usage: sort [OPTION]... [FILE]...
-o 輸出文件
-d 按字典順序排序
-n 按數據大小輸出
-r 按逆序輸出排序結果
-k 指定分類是域上的數字分類
-t 域分隔符,用非空格或tab分隔域
sort -k3 -n -r -t: /etc/passwd
sort -d /etc/passwd
二、WC
Usage: wc [OPTION]... [FILE]...
-c 字符數量~
-l 行數~
-w 統計單詞數量~
wc /etc/passwd
36
三、diff
diff
Usage: diff [OPTION]... FILES
Compare files line by line.
-q 顯示有無差異,不顯示詳細的信息~
-c 顯示全部內文,并標出不同之處~
-b 不檢查空格字符的不同~
-B 不檢查空白行
-r 比較子目錄中的文件~
diff /etc/passwd./passwd.bak
2d1
< bin:x:1:1:bin:/bin:/sbin/nologin
四、grep
Usage: grep [OPTION]... PATTERN [FILE] ...
Search for PATTERN in each FILE or standard input.
-c 只打印匹配的行編號數
-i 匹配文本時忽略大小寫
-n 在每行前顯示其行編號
-v 逆向輸出,打印不匹配的行
-f file 要匹配的字符在文件列表中
cat /etc/passwd |grep -n root
1:root:x:0:0:root:/root:/bin/bash
12:operator:x:11:0:operator:/root:/sbin/nologin
#grep '[Tt]his' file.txt
#grep '^[^#]' file.txt
匹配任意字符
grep 'r..t' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
五、sed
sed
Usage: sed [OPTION]... {script-only-if-no-other-script}[input-file]...
S 替代操作
i 插入命令
a 附加命令
d 刪除全部匹配行
D 刪除首次匹配的行
#sed -n '1,4p' /etc/passwd打印1~4行,-n --quiet以免先打印出passwd的全部內容
#sed '/80/D' file.txt
#sed 's/var/usr/g' file.txt 替換file.txt中全部var為usr
#sed '50,$s/help/man/g' file.txt 從50~最后行替換help為man
sed '/done/d' xj_user_p.log 刪除done
六、awk
Usage: awk [POSIX or GNU style options] -f progfile [--] file...
Usage: awk [POSIX or GNU style options] [--] 'program' file...
NF 當前記錄中的字段數。NR 當前記錄數。
awk -F: '{print NR,$1,$NF}' ./passwd.bak
awk -F: 'NR==5{print NR,$0}' ./passwd.bak 打印出5,15,25...行
5 sync:x:5:0:sync:/sbin:/bin/sync
15 nobody:x:99:99:Nobody:/:/sbin/nologin
25 apache:x:48:48:Apache:/var/www:/sbin/nologin
七、uniq
如果要在文件中查找重復的行,uniq命令會很有用,該命令一般格式為:uniq in_fileout_file
$ more test.txt
aaa
ccc
ccc
ccc
ddd
bbb
eee
123
$ uniq test.txt
aaa
ccc
ddd
bbb
eee
123
$ uniq -d test.txt
ccc
$ uniq -c test.txt
$
綜合示例:
...
數據處理:
找出上海股票漲幅最大的股票?
sort -n -r -k4 t.txt | sed -n '1p'
漲幅>3的股票?
awk '{if ($1>3) print $0} ' t.txt
漲幅在在4~15之間的股票
awk'{if($4>0&&$4<15){print$0}}' t.txt
轉自:http://hi.baidu.com/????????/blog/item/caf21ba89c54ada1ca130c4a
http://hi.baidu.com/edeed/blog/item/b1be513db16db5ed3c6d9727