linux正则表达式

1.搜索特定字符串

[root@localhost ~]# grep  'the' anaconda-ks.cfg   (在anaconda-ks.cfg中查找包含the的行)

[root@localhost ~]# grep -n 'the' anaconda-ks.cfg (-n显示行号)

反选,即不包含the的行

[root@localhost ~]# grep -vn 'the' anaconda-ks.cfg

取得不分大小写的the

[root@localhost ~]# grep -in 'the' anaconda-ks.cfg

2.[]来搜索集合字符  

 搜索test和tast,发现有通用的t?st

[root@localhost ~]# grep -n 't[ae]st' anaconda-ks.cfg  ([]中不论有多少个字符都代表某一个字符,且可以用[a-zA-Z0-9]来表示所有字母和数字)

搜索含有oo的行

[root@localhost yaotameng]# grep -n 'oo' test.txt
2:the mgoongkey
3:The Moonkey

搜索oo且oo前不是g的行
[root@localhost yaotameng]# grep -n '[^g]oo' test.txt
3:The Moonkey

搜索oo,且前边不要大写字母

[root@localhost yaotameng]# grep -n '[^A-Z]oo' test.txt
2:the mgoongkey

只在行首出现的the

[root@localhost yaotameng]# grep -n ^'the' test.txt  (注意这里是单引号 不是[],中括号表示一个字符)
2:the mgoongkey

^在[]内外是不同的意义:

在[]内表示反选,如[^a-z]oo表示oo前不是小写的字母行

在[]外表示在行首 如^[a-z]表示以小写字母开头的行

在行尾出现则用$号

如要找到一.结尾的行

[root@localhost yaotameng]# grep -n '\.$' test.txt
4:bb test a.

找到空白行

[root@localhost yaotameng]# grep -n '^$' test.txt
4:
6:
8:
[root@localhost yaotameng]#

去掉文档中的空白行和#注释行

[root@localhost yaotameng]# grep -v '^$' my.cnf |grep -v '^#'

正则表达是中的.与* 

 .表示一定有一个字符

*表示重复前一个字符0-无穷多次

限定范围{}

[root@localhost yaotameng]# grep -n 'o\{2\}' test.txt  (找到两个O的字符串)
2:the mgoongkey
3:The Moonkey

[root@localhost yaotameng]# grep -n 'go\{2,5\}g' test.txt  (找g,g中间有2-5个O的字符串)
2:the mgoogkey

[root@localhost yaotameng]# grep -n 'go\{2,\}g' test.txt  (找g,g中间有2个以上O的字符串)
2:the mgoogkey

延伸正则表示法

grep需要加-E才能支持延伸表示法

或者直接用命令egrep

+:重复一个活一个以上前一个字符

egrep -n 'go+d' regular_express.txt  (god ,good,gooo...d)

?:0个或一个前一个字符

egrep -n 'go?d' regular_express.txt (gd或者god)

|:用戒( or )癿方式找出数个字符串

egrep -n 'gd|good|dog' regular_express.txt

():找出群组字符串

egrep -n 'g(la|oo)d' regular_express.txt (找出glad或者good)

()+:多个重复群组

echo 'AxyzxyzxyzxyzC' | egrep 'A(xyz)+C'

原文地址:https://www.cnblogs.com/lu215225/p/3012725.html