Linux系統學習之字元處理

youcongtech發表於2017-11-10

管道

管道是一種使用非常頻繁的通訊機制,我們可以使用管道符"|"來連線程式,
由管道連線起來訂單程式可以自動執行,如同有一個資料流一樣,所以管道表現為輸入輸出重定向的一種方法,
它可以把一個命令的輸出內容當作下一個命令的輸入內容,兩個命令之間只需要管道符連線即可

 

 

使用grep搜尋文字

grep [-ivnc] `需要匹配的字元` 檔名
#-i 不區分大小寫
#-c 統計包含匹配的行數
#-n 輸出行號
#-v 反向匹配
例子:
[root@Cfhost-170820-UCNK ~]# cat test.txt
The cat`s name is Tom,What`s the mouse`s name?
The mouse`s NAME is Jerry
They are good friends
[root@Cfhost-170820-UCNK ~]# grep `name` test.txt //搜尋含有`name`的句子
The cat`s name is Tom,What`s the mouse`s name?
[root@Cfhost-170820-UCNK ~]# grep -i `name` test.txt //搜尋含有`name`的句子,忽略大小寫
The cat`s name is Tom,What`s the mouse`s name?
The mouse`s NAME is Jerry
[root@Cfhost-170820-UCNK ~]# grep -c `name` test.txt//含`name`的句子有多少條
1
[root@Cfhost-170820-UCNK ~]# grep -ci `name` test.txt//含`name‘的句子有多少條,大小寫可忽略
2
[root@Cfhost-170820-UCNK ~]# grep -v `name` test.txt //搜尋不含`name`的句子
The mouse`s NAME is Jerry
They are good friends
[root@Cfhost-170820-UCNK ~]# grep -vi `name` test.txt//搜尋不含`name`的句子,大寫的NAME也過濾掉
They are good friends
[root@Cfhost-170820-UCNK ~]# cat test.txt
The cat`s name is Tom,What`s the mouse`s name?
The mouse`s NAME is Jerry
They are good friends
[root@Cfhost-170820-UCNK ~]# cat test.txt | grep -vi `name` ? //以上命令都可以使用管道符改寫,比如上一個命令可以這樣寫,意思都是一樣的
They are good friends

 

使用sort排序

sort [-ntkr] 檔名

#-n 採取數字排序
#-t 指定分隔符
#-k 指定第幾列
#-r 反向排序
[root@Cfhost-170820-UCNK ~]# cat sort.txt
b:3
c:2
a:4
e:5
d:1
f:11
[root@Cfhost-170820-UCNK ~]# cat sort.txt | sort //按字母正向排序
a:4
b:3
c:2
d:1
e:5
f:11
[root@Cfhost-170820-UCNK ~]# cat sort.txt | sort -r //按字母反向排序
f:11
e:5
d:1
c:2
b:3
a:4
[root@Cfhost-170820-UCNK ~]# cat sort.txt | sort -t ":" -k 2 -n
d:1
c:2
b:3
a:4
e:5
f:11

 

使用uniq刪除重複內容

uniq [-ic]
#-i 忽略大小寫
#-c 計算重複內容

[root@Cfhost-170820-UCNK ~]# cat uniq.txt | sort | uniq 
//需要說明的是uniq命令一般需要和sort一起使用,也就是先將檔案使用進行sort排序,然後再使用uniq刪除重複的內容。單獨加上uniq不加sort是沒有效果的。
123
abc

補充說明:
[root@Cfhost-170820-UCNK ~]# cat uniq.txt | uniq
abc
123
abc
123




[root@Cfhost-170820-UCNK ~]# cat uniq.txt | sort | uniq -c 
//使用-c引數就會在每行前面列印出改行重複的次數
      2 123

 

使用cutt擷取文字、使用tr做文字轉換、使用paste做文字合併(還有一個檔案分割用split做,這裡不再說了,我目前想不到它到底有什麼用)

cut -f 指定列 -d `分隔符`

[root@Cfhost-170820-UCNK ~]# cat /etc/passwd | cut -f1 -d `:` root bin daemon admin


tr命令比較簡單,其主要作用在於文字轉換或刪除
[root@Cfhost-170820-UCNK ~]# cat /etc/passwd | tr `[a-z]` `[A-Z]`
ROOT:X:0:0:ROOT:/ROOT:/BIN/BASH
BIN:X:1:1:BIN:/BIN:/SBIN/NOLOGIN

paste的作用在於將檔案按照行進行合併,中間使用tab隔開
[root@Cfhost-170820-UCNK ~]# cat a.txt
a b c
[root@Cfhost-170820-UCNK ~]# cat b.txt
a b c
[root@Cfhost-170820-UCNK ~]# paste a.txt b.txt
a b c    a b c






相關文章