shell正则表达式

Posted 奔跑的金鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell正则表达式相关的知识,希望对你有一定的参考价值。

当一个文件或命令输出中抽取或过滤文本时,可以使用正则表达式(RE),正则表达式是一些特殊或很不特殊的字符串模式的集合。

在Linux中grep、awk、sed均可解释正则

 

1.基本元字符集及其定义

^ 只匹配行首
$ 只匹配行尾
* 一个单字符后紧跟*,匹配0个或多个此单字符
[] 匹配[]内字符。可以使一个单字符,也可以是字符序列。可以使用-代替[]内字符序列范围,如用[1-3]代替[123]
\\ 用来屏蔽一个元字符的特殊含义。\\可以失去它应有的意义
. 匹配任意单字符
pattern\\{\\n} 用来匹配前面pattern出现次数。n为次数
pattern\\{n,\\}m 含义同上,但次数最少为n
pattern\\{n,m\\} 含义同上,但次数在n到m之间

tips:特殊的匹配

ip地址的匹配[root@localhost test]# grep \'[0-9]\\{1,3\\}[.][0-9]\\{1,3\\}[.][0-9]\\{1,3\\}[.][0-9]\\{1,3\\}\'  file01.txt

 

2.详细案例解释说明

现在有file01.txt文件内容如下:

Rolling In the Deep -- Adele
滑向深处
9999999999999999
There\'s a fire starting in my heart,
我心中燃起了火焰
Reaching a fever pitch and it\'s bringing me out the dark
那温度驱走了黑暗
Finally, I can see you crystal clear.
我终于看得清你
Go ahead and sell me out and I\'ll lay your ship bare.
放弃自己的全部赤裸的留在你的心中
See how I leave, with every piece of you
我会一片一片把你剥离我的记忆
Don\'t underestimate the things that I will do.
不要以为我真的不会这么做
There\'s a fire starting in my heart,
心中燃起了火焰

1.^匹配行首

说明:匹配以Th开头的行

[root@localhost test]# grep ^Th file01.txt

image

 

2.$匹配行尾

说明:匹配以dark结尾的行

[root@localhost test]# grep dark$ file01.txt

image

 

3.*匹配0个或单个字符

说明:匹配you出现的行

[root@localhost test]# grep you* file01.txt
image

3.一些其他的grep命令操作

3.1 搜索特定字符串"and"

n为行号

[root@localhost test]# grep -n \'and\' file01.txt

3.2 搜寻不包含特定字符串"and"

[root@localhost test]# grep -vn \'and\' file01.txt

 

3.3 搜索任意大小写"there"这个字符串

[root@localhost test]# grep -in \'there\' file01.txt

 

3.4 利用括号[]来搜索集合字符

搜索fb与ia组合开头的单词

[root@localhost test]# grep -n \'[fb][ia]re\' file01.txt

 

3.5 显示行尾为点的行

[root@localhost test]# grep -n \'\\.$\' file01.txt

 

3.6 显示第二行与第三行数据

[root@localhost test]# cat -An file01.txt |head -n 3|tail -n 2

 

3.7 显示空白行

[root@localhost test]# grep -n  \'^$\' file01.txt

 

3.8 找出含数字的行

[root@localhost test]# grep -n \'[0-9][0-9]*\' file01.txt

以上是关于shell正则表达式的主要内容,如果未能解决你的问题,请参考以下文章

shell编程之正则表达式基础正则表达式

shell函数与正则

shell函数与正则

如何在 shell 脚本中使用正则表达式?

Shell正则表达式之grepsedawk实操笔记

shell编程初步grep及正则表达式