@(Linux)[Linux三劍客之grep及其正則表達式]
HowTo: Use grep Command In Linux / UNIX ?
Can you give me a simple examples of the grep command?
How do I use grep command on Linux, Apple OS X, and Unix-like operating systems?
The grep command is used to search text or searches the given file for lines containing a match to the given strings or words. By default, grep displays the matching lines. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines. grep is considered as one of the most useful commands on Linux and Unix-like operating systems.
1. grep
命令
grep
: grep, egrep, fgrep - print lines matching a pattern
文本搜索工具,根據用戶指定的“模式”對目標文本逐行進行匹配檢查,打印匹配到的行。
模式:由正則表達式字符及文本字符所編寫的過濾條件;
REGEXP:由一類特殊字符及文本字符所編寫的模式,其中有些字符不表示字符字面意義,而表示控制或通配的功能;
正則表達式:
- 基本正則表達式:BRE
- 擴展正則表達式:ERE
格式:
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
參數選項:
-
--color=auto
對匹配到的文本著色顯示 -
-v
顯示不能夠被pattern匹配到的行 -
-i
忽略字符大小寫 -
-o
僅顯示匹配到的字符串 -
-q
靜默模式,不輸出任何信息 -
-A #
after, 后#行 -
-B #
before, 前#行 -
-C #
context, 前后各#行 -
-E
使用ERE
2. 基本正則表達式
2.1 字符匹配
-
.
匹配任意單個字符; -
*
匹配前面的字符任意次 -
[]
匹配指定范圍內的任意單個字符 -
[^]
匹配指定范圍外的任意單個字符 -
[:digit:]
、[:lower:]
、[:upper:]
、[:alpha:]
、[:alnum:]
、[:punct:]
、[:space:]
2.2 貪婪模式
-
.*
任意長度的任意字符 -
\?
匹配其前面的字符0或1次;即前面的可有可無 -
\+
匹配其前面的字符至少1次 -
\{m\}
匹配前面的字符m次 -
\{m,n\}
匹配前面的字符至少m次,至多n次 -
\{0,n\}
匹配前面的字符至多n次 -
\{m,\}
匹配前面的字符至少m次
2.3 位置錨定
-
^
行首錨定;用于模式的最左側 -
$
行尾錨定;用于模式的最右側 -
^PATTERN$
用于模式匹配整行 -
^$
空行 -
^[[:space:]]*$
匹配空格 -
\<
或\b
首錨定,用于單詞模式的左側 -
\>
或\b
詞尾錨定,用于單詞模式的右側 -
\<PATTERN\>
匹配整個單詞
2.4 分組
-
\(\)
將一個或多個字符捆綁在一起,當作一個整體進行處理
在\(ab\+\(xy\)*\)
中,\1
代表ab\+\(xy\)*
,\2
代表xy
Note:
1、分組括號中的模式匹配到的內容會被正則表達式引擎記錄于內部的變量中
2、這些變量的命名方式為: \1, \2, \3, ...
3、\1: 從左側起,第一個左括號以及與之匹配右括號之間的模式所匹配到的字符
4、后向引用:引用前面的分組括號中的模式所匹配字符(而非模式本身)
2.5 實戰演示
1、如果用戶root存在,顯示其默認的shell程序
# id root &> /dev/null && grep "^root\>" /etc/passwd | cut -d: -f7
2、找出/etc/passwd中的兩位或三位數
# grep "\<[0-9]\{2,3\}\>" /etc/passwd
3、顯示/etc/rc.d/rc.sysinit文件中,至少以一個空白字符開頭的且后面存非空白字符的行
# grep "^[[:space:]]\+[^[:space:]]" /etc/grub2.cfg
4、找出"netstat -tan"命令的結果中以'LISTEN'后跟0、1或多個空白字符結尾的行;
# netstat -tan | grep "LISTEN[[:space:]]*$"
3. 擴展的正則表達式
3.1 字符匹配
.
[]
[^]
3.2 次數匹配
*
?
+
{m}
{m,n}
3.3 錨定
^
$
-
\<
,\b
-
\>
,\b
3.4 分組
()
后向引用:
\1, \2, ...
或者使用 a | b
C | cat
3.5 實戰演示
1、顯示當前系統root、centos或user1用戶的默認shell和UID;
# grep -E '^(root|centos|user1)\>' /etc/passwd | cut -d: -f1,3,7
2、找出/etc/rc.d/init.d/functions文件(centos6)中某單詞后面跟一個小括號的行;
# grep -E -o "^[_[:alpha:]]+\(\)" /etc/rc.d/init.d/functions
3、使用echo輸出一絕對路徑,使用egrep取出其基名;
# echo "/mnt/sdc" | grep -E -o "[^/]+/?$" | cut -d"/" -f1
4. egrep
and fgrep
4.1 egrep
命令
egrep = grep -E
4.2 fgrep
命令
fgrep
:不支持正則表達式搜索,能夠很快的進行搜索