linux中grep命令


grep [option] "pattern" 文件名
grep "root" /etc/passwd 過濾帶有root 字符

正則表達式元字符
1匹配單個字符的元字符
. 表示任意單個字符
[root@localhost ~]# grep "r..t" /etc/passwd
[abc] 或者
[root@localhost ~]# grep "r[aA]t" /tmp/1.txt

- 連續的字符范圍
[a-z] [A-Z] [a-zA-Z] [0-9] [a-zA-Z0-9]

[root@localhost ~]# grep "r[A-Z]t" /tmp/1.txt
rAt
[root@localhost ~]# grep "r[0-9]t" /tmp/1.txt
r8t
[root@localhost ~]# grep "r[a-zA-Z0-9]t" /tmp/1.txt
r8t
rAt

^ 取反
[^a-z]
[root@localhost ~]# grep "r[^0-9]t" /tmp/1.txt
rAt


特殊字符集:
[[:punct:]] 任意單個標
[root@localhost ~]# grep -En "r[[:punct:]]t" /tmp/1.txt
11:r,t
12:r?t
13:r"t"

[[:space:]]任意單個空白字符
[root@localhost ~]# grep -En "r[[:space:]]t" /tmp/1.txt
14:r t


2 匹配字符出現的位置
1) ^string 以string 開頭
2)^[rbh] 查找以rbh 開頭-----取反 ^[^rbh]
[root@localhost ~]# grep "^[^rbh]" /etc/passwd

3) string& 以string 結尾
[root@localhost ~]# grep "bash&" /etc/passwd
[root@localhost ~]# grep "nologin&" /etc/passwd | wc -l

4) ^& 空行
[root@localhost ~]# grep "^&" /etc/fstab | wc -l

顯示/etc下的目錄名
[root@localhost ~]# ls -l /etc/ | grep "^d"


3 匹配字符出現的次數

* 匹配前一個字符出現的任意次 ab*: a ab abb abbb
[root@localhost ~]# grep "ab*" /tmp/2.txt
.* 任意字符

? 前一個字符最多出現一次 最少出現0次或一次
* 0 or 多次
+ one or more times.(一次或者多次)
{n} 字符精確出現幾次
{n,} 最少n次 多了不限
{,m} 最多m次
{n,m} 最少n次 做多m次

\? 0次或者1次 可有可無
[root@localhost ~]# grep "ab\?" /tmp/2.txt

\+ 1次或者多次 最少1次
[root@localhost ~]# grep "ab\+" /tmp/2.txt

\{2\} 精確匹配2次
[root@localhost ~]# grep "ab\{2\}" /tmp/2.txt

\{2,5\} 最少2次 最多5次
[root@localhost ~]# grep "ab\{2,5\}" /tmp/2.txt

\{2,\} 最少2次
[root@localhost ~]# grep "ab\{2,\}" /tmp/2.txt

 

分組 \(ab)\+
[root@localhost ~]# grep "\(ab\){2,\}" /usr/share/dict/words

 


option選項:
1) -i 忽略大小寫
[root@localhost ~]# grep -i "^r" /tmp/1.txt
2) -o 僅顯示符合正則表達式的內容,不再顯示整行
xpl@localhost ~]$ grep -o "r..t" /etc/passwd
3) -v 反向過濾
[root@localhost ~]# grep -v "^#" /etc/fstab
4) -e 根據多個選項過濾文本
[root@localhost ~]# grep -e "^&" -e "^#" /etc/fstab
[root@localhost ~]# grep -v -e "^&" -e "^#" /etc/fstab 不顯示
5)-E 支持擴展正則表達式
[root@localhost ~]# grep -E "\(ab\){2,\}" /usr/share/dict/words

 

cpu信息
[root@localhost ~]# cat /proc/cpuinfo
[root@localhost ~]# grep -E "vmx|svm" /proc/cpuinfo

6) -A n 同時顯示符合條件的后n行
[root@localhost ~]# ifconfig eth0 | grep -A 2 "network"
-B n 同時顯示符合條件前n
[root@localhost ~]# ifconfig eth0 | grep -B 2 "network"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM