前提
LANG=C
alias grep=‘grep —color=auto'
背誦下來
[:alnum:] [:alpha:] [:upper:] [:lower:] [:digit:]
顯示帶有 the的行
[root@bird ~]# grep -n 'the' regular_express.txt
顯示不帶 the的行
[root@bird ~]# grep -vn 'the' regular_express.txt
顯示帶有無論大小寫 the的行
[root@bird ~]# grep -in 'the' regular_express.txt
搜尋 test 或 taste 這兩個單字( t?st)
[root@bird ~]# grep -n 't[ae]st' regular_express.txt
搜尋帶有oo 且前邊不是g的
[root@bird ~]# grep -n '[^g]oo' regular_express.txt
oo前邊不是小寫字母的行
[root@bird ~]# grep '[^[:lower:]]oo' regular_express.txt
行首有the的行
[root@bird ~]# grep -n '^the' regular_express.txt
小寫字母開頭的行
[root@bird ~]# grep -n '^[[:lower:]]' regular_express.txt
不是英文字母開頭的行
[root@bird ~]# grep -n '^[^[:alpha:]]' regular_express.txt
不要空白行和開頭是#的行
[root@bird ~]# grep -v '^$' anaconda-ks.cfg | grep -v '^#'
字符串 開頭結尾都是g 中間至少包含一個o的 行
[root@bird ~]# grep -n 'goo*g' regular_express.txt
字符串 開頭結尾都是g 當中的字節可有可無(零個或多個任意字節)
[root@bird ~]# grep -n 'g.*g' regular_express.txt
找出兩個到五個 o 的連續字串
[root@bird ~]# grep -n 'o\{2,5\}' regular_express.txt
字符串 開頭是g 接着是至少兩個o 然後再接一個g
[root@bird ~]# grep -n 'go\{2,5\}g' regular_express.txt
字符串 開頭是g 接着是至少兩個o
[root@bird ~]# grep -n 'go\{2,\}g' regular_express.txt
. (小數點):代表『一定有一個任意字節』的意思;
* (星星號):代表『重複前一個字節, 0 到無窮多次』的意思,爲組合形態
sed工具
-n :使用安靜(silent)模式。在一般 sed 的用法中,所有來自 STDIN
的數據一般都會被列出到螢幕上。但如果加上 -n 參數後,則只有經過
sed 特殊處理的那一行(或者動作)纔會被列出來。
-e :直接在命令列模式上進行 sed 的動作編輯;
-f :直接將 sed 的動作寫在一個文件內, -f filename 則可以運行 filename 內的
sed 動作;
-r :sed 的動作支持的是延伸型正規表示法的語法。(默認是基礎正規表示法語法)
-i :直接修改讀取的文件內容,而不是由螢幕輸出。
動作說明: [n1[,n2]]function
n1, n2 :不見得會存在,一般代表『選擇進行動作的行數』,舉例來說,如果我的動作
是需要在 10 到 20 行之間進行的,則『 10,20[動作行爲] 』
function 有底下這些咚咚:
a :新增, a 的後面可以接字串,而這些字串會在新的一行出現(目前的下一行)~
c :取代, c 的後面可以接字串,這些字串可以取代 n1,n2 之間的行!
d :刪除,因爲是刪除啊,所以 d 後面通常不接任何咚咚;
i :插入, i 的後面可以接字串,而這些字串會在新的一行出現(目前的上一行);
p :列印,亦即將某個選擇的數據印出。通常 p 會與參數 sed -n 一起運行~
s :取代,可以直接進行取代的工作哩!通常這個 s 的動作可以搭配
正規表示法!例如 1,20s/old/new/g 就是啦!
將 /etc/passwd 的內容列出並且列印行號,同時,
將第 2~5 行刪除!
[root@bird ~]# nl /etc/passwd | sed '2,5d'
將第 3~最後一行刪除
[root@bird ~]# nl /etc/passwd | sed '3,$d'
在第二行後 加上 ‘drink tea'
[root@bird ~]# nl /etc/passwd | sed '2a drink tea'
在第二行前 加上 ‘drink tea'
[root@bird ~]# nl /etc/passwd | sed '2i drink tea'
在第二之前 添加多行
[root@bird ~]# nl /etc/passwd | sed '2a drink tea\
> drink beer?'
將2-5行取代成No2-5 number
[root@bird ~]# nl /etc/passwd | sed '2,5c No2-5 number'
只取出5-7行
[root@bird ~]# nl /etc/passwd | sed -n '5,7p'
sed ’s/原內容/新內容/g'
[root@bird ~]# ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'
取出只含有MAN的行 並且去掉#註釋行和空白行
[root@bird ~]# cat /etc/man.config | grep 'MAN' | sed 's/#.*$//g' | sed '/^$/d'
直接修改文件內容
[root@bird ~]# sed -i 's/\.$/\!/g' regular_express.txt
延伸正則寫法
去除空白行和行首是#的行
[root@bird ~]# egrep -v '^$|^#' regular_express.txt
一個或以上的o
[root@bird ~]# egrep -n 'go+d' regular_express.txt
零個或一個o
[root@bird ~]# egrep -n 'go?d' regular_express.txt
[root@bird ~]# egrep --color=auto 'g(la|oo)d' regular_express.txt
[root@bird ~]# echo 'AxyzxyzxyzxyzD' | egrep 'A(xyz)+D'