1. 程式人生 > >【shell】正則表達式

【shell】正則表達式

alt blog 溫度 can href aci txt cnblogs ble

當一個文件或命令輸出中抽取或過濾文本時,可以使用正則表達式(RE),正則表達式是一些特殊或很不特殊的字符串模式的集合。

在Linux中grep、awk、sed均可解釋正則

1.基本元字符集及其定義

^ 只匹配行首
$ 只匹配行尾
* 一個單字符後緊跟*,匹配0個或多個此單字符
[] 匹配[]內字符。可以使一個單字符,也可以是字符序列。可以使用-代替[]內字符序列範圍,如用[1-3]代替[123]
\ 用來屏蔽一個元字符的特殊含義。\可以失去它應有的意義
. 匹配任意單字符
pattern\{\n} 用來匹配前面pattern出現次數。n為次數
pattern\{n,\}m 含義同上,但次數最少為n
pattern\{n,m\} 含義同上,但次數在n到m之間

2.詳細案例解釋說明

現在有file01.txt文件內容如下:

Rolling In the Deep -- Adele
滑向深處
9999999999999999
There‘s a fire starting in my heart,
我心中燃起了火焰
Reaching a fever pitch and it‘s bringing me out the dark
那溫度驅走了黑暗
Finally, I can see you crystal clear.
我終於看得清你
Go ahead and sell me out and I‘ll lay your ship bare.
放棄自己的全部赤裸的留在你的心中
See how I leave, with every piece of you
我會一片一片把你剝離我的記憶
Don‘t underestimate the things that I will do.
不要以為我真的不會這麽做
There‘s a fire starting in my heart,
心中燃起了火焰

1.^匹配行首

說明:匹配以Th開頭的行

[root@localhost test]# grep ^Th file01.txt

技術分享圖片

2.$匹配行尾

說明:匹配以dark結尾的行

[root@localhost test]# grep dark$ file01.txt

技術分享圖片

3.*匹配0個或單個字符

說明:匹配you出現的行

[root@localhost test]# grep you* file01.txt
技術分享圖片

3.一些其他的grep命令操作

3.1 搜索特定字符串"and"

n為行號

[root@localhost test]# grep -n ‘and‘ file01.txt


3.2 搜尋不包含特定字符串"and"

[root@localhost test]# grep -vn ‘and‘ file01.txt

【shell】正則表達式