shell中正则表达式的使用

shell中正则表达式的使用

基本正则列表

正则符号 描述
^ 匹配行首
$ 匹配行尾
[ ] 集合,匹配集合中任意单个字符
[^] 对集合取反
. 匹配任意单个字符
* 匹配前一个字符任意次数(*不允许单独使用)
匹配前一个字符n到m次
匹配前一个字符n次
匹配前一个字符n次及以上
\(\) 保留
{ n , m } 匹配前一个字符n到m次
{n}匹配前一个字符n次
{n,} 匹配前一个字符n次及以上

扩展正则列表

正则符号 描述
+ 匹配前一个字符至少一次
匹配前一个字符至多一次
匹配n到m次
() 组合为整体,保留
| 或者
\b 单词边界

示例:

基本正则符号
^匹配开头字串     $匹配结尾字串       ^$匹配空行
grep root 文件名 //找有root的行
grep ^root 文件名		//找有以root开头的行
grep bash$ 文件名		//找有以bash结尾的行
grep ^$ 文件名			//找空行
// [] [^]
grep [rot] txt		//查找有字母r或者o或者t的行
grep [bin] txt		//查找有字母b或者i或者n的行
grep bas[hg] txt	//查找有bash或者basg的行
grep [^rot] txt		//找出拥有除了r或者o或者t的行

grep "[a-z]" txt     //找有小写字母的行
grep "[^a-z]" txt	 //找拥有除了小写字母的行
grep "[A-Z]" txt	 //找有大写字母的行
grep "[A-Z]" /etc/shadow
grep "[^A-Z]" /etc/shadow  //找拥有除了大写字母的行
grep "[a-Z]" /etc/shadow   //找所有字母
grep "[^a-Z]" /etc/shadow  //不找字母
grep "[0-9]" /etc/shadow   //找数字
// . *
grep "roo." txt	  //找roo开头,后面追加1个任意字符的行
grep "ro.." txt	 //找ro开头,后面追加2个任意字符的行
grep "." txt	 //找任意单个字符
grep ".oot" txt  //找某字符开头后面是oot的行
grep "*" txt     //不能单独使用什么也找不到
grep "ro*ot" txt  //找root,第一个o可以出现任意次
grep "ro*t" txt   //找rot,o可以出现任意次
grep "bo*i" txt   //找boi,o可以出现任意次
grep ".*" txt		//找任意
// \{n,m\}  \{n\}  \{n,\}
grep "ro\{2,3\}t" txt   //找root或者rooot
grep "ro\{2\}t" txt		//找root
grep "ro\{3\}t" txt	    //找rooot
grep "ro\{1\}t" txt		//找rot
grep "ro\{2,\}t" txt 	//找rot,o可以出现2次以及2次以上
grep "ro\{3,\}t" txt    //找rot,o可以出现3次以及3次以上
grep "ro\{1,\}t" txt    //找rot,o可以出现1次以及1次以上

// 扩展正则 + ? {n,m}
grep "ro+t" txt        //grep不支持扩展正则
grep -E "ro+t" txt 	   //增加-E选项后支持
egrep "ro+t" txt	 //或egrep,找rot,o可以出现1次以及多次
egrep "ro?t" txt   //找rot,o可以出现0次或1次
egrep "ro?ot" txt   //找root,第一个o可以出现0次或1次
grep "ro\{0,1\}ot" txt  //使用基本正则实现相同效果 
egrep "ro{0,1}ot" txt  //扩展正则更精简

\b (空,空格,tab,特殊符号)

egrep "r|o|t" txt     //找r或o或t
egrep "bash|nologin"  txt    //找bash或nologin
egrep "\bbin\b" txt	   //找bin,前后不能是数字,字母,下划线

posted @ 2022-03-24 18:00  菜鸟成长历程  阅读(506)  评论(0编辑  收藏  举报