1. 環(huán)境
vim ahappychild.txt
My hose is red - a little house;
A happy child am I.
I laugh and play the whole day long,
I hardly ever cry.
I have a tree, a green, green tree,
To shade me from the sun;
And under it I often sit,
When all my play is done.
vim sortuniq.txt
Canepa,Gabriel:20140808:15
Doe,John:20140325:30
Null,Dave:20141009:5
Doe,John:20140324:30
Null,Dave:20140709:5
Canepa,Gabriel:20140808:15
Doe,John:20140311:30
Null,Dave:20141009:5
Doe,Jane:20140510:10
Canepa,Gabriel:20140608:15
Doe,john:20140324:30
2. sed
1. 將小寫y替換成大寫Y核畴,輸出到ahappychild2.txt
sed 's/y/Y/g' ahappychild.txt > ahappychild2.txt
2. 我們要用一個(gè)符號來替換一個(gè)文字,與此同時(shí)我們將把一行最開始出現(xiàn)的第一個(gè) I 替換為 You冲九。
如果要在替換文本中搜索或者替換特殊字符(如 /谤草,\,&)莺奸,需要使用反斜杠對它進(jìn)行轉(zhuǎn)義丑孩。
sed 's/and/\&/g;s/^I/i/g' ahappychild.txt
3. 將會顯示 /var/log/messages 中從12月13日開始的頭五行。
sed -n '/^Dec 13/p' /var/log/messages|sed -n 1,5p
4. 取消開頭注釋和空行
sed '/^#\|^$/d' /etc/selinux/config
3. uniq
uniq 命令允許我們返回或者刪除文件中重復(fù)的行灭贷,默認(rèn)寫到標(biāo)準(zhǔn)輸出温学。我們必須注意到,除非兩個(gè)重復(fù)的行相鄰甚疟,否則uniq 命令不會刪除他們仗岖。因此,uniq 經(jīng)常和一個(gè)前置的 sort 命令(一種用來對文本行進(jìn)行排序的算法)搭配使用古拴。默認(rèn)情況下箩帚,sort 使用第一個(gè)字段(用空格分隔)作為關(guān)鍵字段。要指定一個(gè)不同的關(guān)鍵字段黄痪,我們需要使用 -k 選項(xiàng)紧帕。
1. 查看linux每天產(chǎn)生的日志數(shù)
cat /var/log/messages |uniq -c -w 6
2. 查詢有多少個(gè)捐贈者
cat sortuniq.txt |cut -d: -f1|sort|uniq
4. tr
tr 命令可以用來從標(biāo)準(zhǔn)輸入中轉(zhuǎn)換(改變)或者刪除字符,并將結(jié)果寫入到標(biāo)準(zhǔn)輸出中。
1. 小寫變大寫
cat sortuniq.txt | tr [:lower:] [:upper:]
2.輸出中的分隔符為一個(gè)空格是嗜。
cd /
ls -l |tr -s ' '
5. cut
1. 從 /etc/passwd 中提取用戶賬戶和他們被分配的默認(rèn) shell(-d 選項(xiàng)允許我們指定分界符愈案,-f 選項(xiàng)指定那些字段將被提取)鹅搪。
cat /etc/passwd |cut -d: -f1,7
6. 綜合實(shí)例
1. 能過last查詢r(jià)oot用戶的IP登陸情況(去重)
last|grep root|tr -s ' '|cut -d' ' -f1,3|sort -k2|uniq -c