歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell中正則表達式

shell中正則表達式

日期:2017/3/1 9:56:52   编辑:SHELL編程

看了鳥哥的linux總結一下,以備後面用到。

1.一些特殊符號

2.行首控制符^、行尾控制符$

找出行首包含the的:
[root@www ~]# grep -n '^the' regular_express.txt
開始為小寫字母的:
# grep -n '^[a-z]' regular_express.txt
那如果我不想要開頭是英文字母:
# grep -n '^[^a-zA-Z]' regular_express.txt
開頭不是英文字母的:
[root@www ~]# grep -n '^[^a-zA-Z]' regular_express.txt
顯示空白行:
[root@www ~]# grep -n '^$' regular_express.txt
不顯示空白行和帶#號的行:
# grep -v '^$' /etc/syslog.conf | grep -v '^#'

3.正則表達式中。“.”代表絕對有一個任意字符的意思;而“*”代表重復前一個到無窮次的意思

尋找g開頭和d結束的包含四個字符:
# grep -n 'g..d' regular_express.txt
尋找oo, ooo, oooo 等等癿數據,也就是說,至少要有兩個o 以上:
# grep -n 'ooo*' regular_express.txt(前兩個o必須存在,第三個o重復次數不限)
尋找g開頭和g結束的字符串,中間可有可無
[root@www ~]# grep -n 'g.*g' regular_express.txt
我想要找出兩個到五個o的連續字符串,該如何作?這時候就得要使用到限定范圍癿字符{}了。 但因為 {} 在 shell 是有特殊意義的。必須要使用跳脫字符 \ 讓他失去特殊意義才行。至亍 {}的語法法是這樣的,假設我要找到兩個o的字符串,可以是:
[root@www ~]# grep -n 'go\{2,5\}g' regular_express.txt

4.正則表達式中特殊字符

(1) ^word:待搜尋的字符串(word)在行首!

搜尋“#”開始的:grep -n '^#' regular_express.txt

(2)word$:將行尾為 !癿那一行打印出杢,幵列出行號

搜尋“!”結尾的:grep -n '!$' regular_express.txt

(3)\:將特殊符號癿特殊意義去除!

搜尋噸有單引號 '的那一行:grep -n \' regular_express.txt

(4)*:重復零個到無窮多個癿前一個字符

搜尋es開頭,後面s重復2次以上的:grep -n 'ess*' regular_express.txt

(5)[list]:字符集合的RE字符,裡面列出想要選擇的字符!

搜尋gl或者gd的行:grep -n 'g[ld]' regular_express.txt

(6)字符集合的RE字符,裡面列出不要的字符串串范圍!

搜尋的字符串可以是 (oog) (ood)但不能是 (oot):rep -n 'oo[^t]' regular_express.txt

(7)[n1-n2]:字符集合的 RE字符,裡面列出想要包括的字符范圍!

搜尋含有數字的:grep -n '[0-9]' regular_express.txt

(8)\{n,m\}:連續 n到 m個的『前一個RE字符』

搜尋在g不g之間有2個到3個o存在的字符串:grep -n 'go\{2,3\}g' regular_express.txt

Copyright © Linux教程網 All Rights Reserved