首页 > 系统服务 > 详细

shell脚本之正则表达式

时间:2019-05-27 18:23:32      阅读:100      评论:0      收藏:0      [点我收藏+]
一、基础正则表达式实例:
元字符总结:
技术分享图片
在Linux系统中常见的文件处理工具中grep和sed支持基础正则表达式。

grep命令选项:

                        -i:查找时不区分大小写;
                        -v:查找时反向输出,如查找不包含某些字符的内容;
                        -n:表示查找出结果后显示行号;

这三个选项可以结合使用,如“-in”,查找时不区分大小写并显示行号。
示例①:

[root@localhost ~]# grep -n ‘the‘ test.txt                   #查找test文件中包含字符“the”的行
#可以将选项改为“-vn”来查找不包含“the”的行。

示例②:

[root@localhost ~]# grep -n "sh[io]rt" test.txt                   #[io]表示匹配 i 或o的显示出来
#[ ]中无论有几个字符都仅代表匹配一个字符即可。

示例③:

[root@localhost ~]# grep -n ‘oo‘ test.txt                 #查找包含字符“oo”的行。
[root@localhost ~]# grep -n ‘ooo*‘ test.txt              #查找包含至少两个o以上的字符串。
[root@localhost ~]# grep -n ‘o\{2\}‘ test.txt             #查找包含两个“o”的字符串。
 [root@localhost ~]# grep -n ‘o\{2,5\}‘ test.txt          #查找包含2~5个o的字符串。
 [root@localhost ~]# grep -n ‘o\{2,\}‘ test.txt             #查找包含两个以上“o”的字符串。

示例④:

[root@localhost ~]# grep -n ‘[^w]oo‘ test.txt           #查找“oo”前面不是w的字符串。
[root@localhost ~]# grep -n ‘[^a-z]oo‘ test.txt          #查找oo前不是小写字母的行。
[root@localhost ~]# grep -n ‘[0-9]‘ test.txt               #查找包含数字的行。
[root@localhost ~]# grep -n ‘^the‘ test.txt             #查找以“the”开头的行。
[root@localhost ~]# grep -n ‘^[a-z]‘ test.txt             #查找以小写字母开头的行。
[root@localhost ~]# grep -n ‘^[A-Z]‘ test.txt            #查找以大写字母开头的行。 
[root@localhost ~]# grep -n ‘^[^a-zA-Z]‘ test.txt       #查找不以字母开头的行。
#     “^”在[ ] 号外面表示定位行首,也就是以某些内容开头,若在[ ]内则表示反向选择。
[root@localhost ~]# grep -n ‘\.$‘ test.txt             #查找以 “ .  ” 结尾的行。
[root@localhost ~]# grep -n ‘w..d‘ test.txt             #查找w开头,中间两个未知字符,d结尾的行。
[root@localhost ~]# grep -n ‘woo*d‘ test.txt     #查找w开头d结尾,中间至少包含一个o的字符串。
[root@localhost ~]# grep -n ‘w.*d‘ test.txt        #查找w开头d结尾,中间的字符可有可无的字符串。
[root@localhost ~]# grep -n ‘[0-9][0-9]*‘ test.txt            #查询任意数字所在行

二、扩展正则表达式
一般来说基础正则表达式足以我们使用了,但如果想要简化整个指令,那么就可以使用扩展正则表达式,如果使用扩展正则表达式,需要使用egrep或awk命令,常见的扩展正则表达式的元字符主要包括如下几个:
技术分享图片

shell脚本之正则表达式

原文:https://blog.51cto.com/14154700/2400958

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!