正則表達式

 

grep,egrep,fgrep

grep:Global Research Pattern 根據模式,搜索文本,並將符合模式的文本行顯示出來。
Pattern :由文本字符和正則表達式的元字符組合成的匹配。

NAME
       grep, egrep, fgrep - print lines matching a pattern

SYNOPSIS
       grep [options] PATTERN [FILE...]
       grep [options] [-e PATTERN | -f FILE] [FILE...]

[root@localhost 3307]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

-i 忽略大小寫
--color= 加眼神選項
[root@localhost 3307]# alias grep='grep --color'  可以添加別名

-v 顯示沒有模式匹配的行
-o 只顯示被模式匹配到的字符串

正則表達式:REGular EXPression ,REGEXP

* 任意長度的任意字符
?任意單個字符
. 匹配任意單個字符

.* 任意長度的任意字符

\? 匹配其前面的字符1次或0次
\{m,n\} 斜線逃逸字符 匹配其前面的字符至少m次,至多n次
    \{1,\}
    \{0,3\}
位置錨定:

^ 錨定行首,此字符後面的任意內容必須出現首行

[root@localhost 3307]# grep '^root' /etc/passwd
root:x:0:0:root:/root:/bin/bash

$ 錨定行尾,此字符前面的任意內容必須出現行尾

[root@localhost 3307]# grep 'bash$' /etc/passwd
root:x:0:0:root:/root:/bin/bash
cms:x:501:501::/home/cms:/bin/bash
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash

^$ 匹配空白行
grep -v '^$' /etc/inittab 不顯示空白字符

[] 匹配指定範圍內的任意單個字符

[^] 匹配指定滿園外的任意單個字符

字符集合
    [:digit:],[:lower:],[:upper:],[:punct:],[:space:]

[root@localhost 3307]# grep '[[:digit:]]$' /etc/inittab 
#   5 - X11
l0:0:wait:/etc/rc.d/rc 0
l1:1:wait:/etc/rc.d/rc 1
l2:2:wait:/etc/rc.d/rc 2
l3:3:wait:/etc/rc.d/rc 3
l4:4:wait:/etc/rc.d/rc 4
l5:5:wait:/etc/rc.d/rc 5
l6:6:wait:/etc/rc.d/rc 6
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6
# Run xdm in runlevel 5

\<或 \broot 錨定詞首,其後面的任意字符必須作爲單詞的首部出現  \<root 以root爲詞首的 \broot
\> 或 root\b 錨定詞尾,其前面的任意字符必須作爲單詞的尾部出現  root\> 以root爲詞尾的 root\b
\<root\>

分組
\(\)
    \(ab\)*
\1,\2  引用括號的內的次數
grep '^\1([0-9]):\1.*\1$' /etc/inittab
==================================================================================================
擴展正則表達式
Baseic REGEXP 基本正則表達式
Extended REGEXP 擴展正則表達式  默認工作在貪婪模式下
字符匹配
.
[]
[^]
次數匹配
*

+ 至少一次,匹配其前面的字符至少1次
{m,n} 不需要使用\線轉意

位置錨定字符都一樣

分組:
() 不需要加反斜線 \
\1, \2, \3 ....

或者

a| b   代表 or

grep --color -E 'C|cat' rg  代表匹配大寫小寫Cc

fgrep : fast 快速的,不支持正則表達式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章