正則表達式概述
正則表達式是一種定義的規則,Linux工具可以用它來過濾文本。
基礎正則表達式
純文本
[root@node1 ~]# echo "this is a cat" | sed -n '/cat/p'this is a cat[root@node1 ~]# echo "this is a cat" | gawk '/cat/{print $0}'this is a cat
正則表達式的匹配非常挑剔,尤其需要記住,正則表達式區分大小寫。
特殊字符
正則表達式識別的特殊字符包括:
.*[]^${}/+?|()
如果要使用某個特殊字符作為文本字符,就必須轉義,一般用(/)來轉義。
[root@node1 ~]# echo "this is a $" | sed -n '//$/p'this is a $
錨字符
有兩個特殊字符可以用來將模式鎖定在數據流的行首或行尾
脫字符(^)定義從數據流中文本行的行首開始的模式。
美元符($)定義了行尾錨點。
[root@node1 ~]# echo "this is a cat" | sed -n '/^this/p'this is a cat[root@node1 ~]# echo "this is a cat" | sed -n '/cat$/p'this is a cat
在一些情況下可以組合使用這兩個命令
1.比如查找只含有特定文本的行
[root@node1 ljy]# more test.txt this is a dogwhathowthis is a catis a dog[root@node1 ljy]# sed -n '/^is a dog$/p' test.txtis a dog[root@node
2.兩個錨點組合起來,可以直接過濾空白行
[root@node1 ljy]# more test.txt this is a dogwhathow this is a catis a dog[root@node1 ljy]# sed '/^$/d' test.txt this is a dogwhathowthis is a catis a dog
點號字符
點號用來匹配除換行符外的任意單個字符,他必須匹配一個字符。
[root@node1 ljy]# more test.txtthis is a dogwhathowthis is a catis a dogat[root@node1 ljy]# sed -n '/.at/p' test.txtwhatthis is a cat
字符組
限定待匹配的具體字符,使用字符組。使用方括號來定義一個字符組。
[root@node1 ljy]# more test.txtthis is a dogthis is a Dogthis is a DoGthis is a cat[root@node1 ljy]# sed -n '/[dD]og/p' test.txtthis is a dogthis is a Dog[root@node1 ljy]# sed -n '/[dD]o[gG]/p' test.txt this is a dogthis is a Dogthis is a DoG
排除型字符組
要排除某些特定的元素,要在字符組前面加個脫字符。
[root@node1 ljy]# sed -n '/[dD]o[gG]/p' test.txt this is a dogthis is a Dogthis is a DoG[root@node1 ljy]# sed -n '/[^D]og/p' test.txt this is a dog
區間
正則表達式會包括此區間內的任意字符。
[root@node1 ljy]# more test.txt1231231231121222222412345341613vsdvsqwer123441231234534211444444[root@node1 ljy]# sed -n '/^[0-9][0-9][0-9][0-9][0-9]$/p' test.txt1234534211
新聞熱點
疑難解答