shell编程-正则表达式
来源:互联网 发布:软件开发的方法 编辑:程序博客网 时间:2024/05/13 23:58
1、正则表达式是什么
正则表达式是用于字符排列和匹配模式的一种语法规则。它主要用于字符串的模式分割、匹配、查找及替换操作。
2、正则表达式与通配符
- 正则表达式用来在文件中匹配符合条件的字符串,正则是包含匹配。grep、awk、sed等命令可以支持正则表达式。
- 通配符用来匹配符合条件的文件名,通配符是完全匹配。ls、find、cp这些命令不支持正则表达式,所以只能使用shell自己的通配符进行匹配了。
通配符:
- *:匹配任意内容
- ?: 匹配任意一个内容
- []:匹配中括号中的一个字符
3、基础正则表达式
补充:
?()属于扩展正则
修改~/.bashrc配置文件,为grep起别名,将匹配出来的用颜色显示alias grep=’grep –color=auto’
例如:*号的示例
[root@localhost home]# grep aa* test.txt aaaaaaaaaaaaaaaabaabb
例如
“.”:匹配除了换行符外任意一个字符
“s..d”:会匹配在s和d这两个字母之间一定有两个字符的单词
[root@localhost home]# grep "s..d" test.txt saidsoidsdkdkdkd
“s.*d”:匹配在s和d字母之间有任意字符
[root@localhost home]# grep "s.*d" test.txt saidsoidsdkdkdkd
“.*”:匹配所有内容
[root@localhost home]# grep ".*" test.txt aaaaaaaaaaaaaaaabaabbbbbbbbbbbbbbbbsaidsoidsdkdkdkd
例如
“^”匹配行首,”$”匹配行尾
“^M”:匹配以大写“M”开头的行
[root@localhost home]# grep "^a" test.txt aaaaaaaaaaaaaaaabaabb
“n$”:匹配以小写“n”结尾的行
[root@localhost home]# grep "b$" test.txt abaabbbbbbbbbbbbbbbb
“^$”:匹配空白行显示,增加-n选项,显示行号
[root@localhost home]# grep -n "^$" test.txt 6:9:15:16:
例如
“[]” : 匹配中括号中指定的任意一个字符,只匹配一个字符。
“s[ao]id”:匹配s和i字母中间,要么是a,要么是o的字符串
[root@localhost home]# grep -n "s[ao]id" test.txt 17:said18:soid
“[0-9]”:匹配包括任意一个数字的行
[root@localhost home]# grep -n "[0-9]" test.txt 22:6adfadfadf823:jladf800237825:ladfjadf727:333333333329:2222222222
“^[a-z]”:匹配用小写字母开头的行
[root@localhost home]# grep "^[a-z]" test.txt aaaaaaaaaaaaaaaabaabbbbbbbbbbbbbbbbsaidsoidsdkdkdkdjladf8002378ladfjadf7
“[a-z]$”:匹配用小写字母结尾的行
[root@localhost home]# grep "[a-z]$" test.txt aaaaaaaaaaaaaaaabaabbbbbbbbbbbbbbbbsaidsoidsdkdkdkd[root@localhost home]# grep "^[a-z]$" test.txt ab[root@localhost home]# grep "^[a-z][a-z]$" test.txt aaabbb
“[^]”:匹配除中括号的字符以外的任意字符。(说明:^放在中括号内)
“^[^a-z]”:匹配不用小写字母开头的行
[root@localhost home]# grep "^[^a-z]" test.txt 6adfadfadf833333333332222222222
“^[^a-zA-Z]”:匹配不用字母开头的行
[root@localhost home]# grep "^[^a-zA-Z]" test.txt 6adfadfadf833333333332222222222
“\”:转义字符,作用让特殊的字符丧失意义
“.$”:匹配使用”.”结尾的行
[root@localhost home]# grep "\.$" test.txt 6adfadfadf8.
“\{n\}”:表示其前面的字符恰好出现n次
“a\{3\}”:匹配a字母连续出现三次的字符串。
注意:至少重复3次,匹配出来的结果显示超过3个字符串也会显示到结果中
[root@localhost home]# grep "a\{3\}" test.txt aaaaaaaaaaaa
“[0-9]\{3\}”:匹配包括连续的三个数字的字符串
要想准确查找,需要加定界符
0 0
- shell编程 正则表达式
- Shell编程-正则表达式
- shell编程-正则表达式
- shell编程-正则表达式
- shell编程之正则表达式
- shell编程笔记-正则表达式
- shell编程正则表达式介绍
- shell编程之正则表达式
- Shell编程之正则表达式
- shell编程之正则表达式
- Linux Shell编程-正则表达式
- shell 编程之正则表达式
- shell编程之正则表达式
- shell 编程(一)之 正则表达式
- shell编程基础【六】---正则表达式
- shell编程之正则表达式基础
- Shell编程学习---第七篇:正则表达式
- Linux shell编程 6 ---- 正则表达式
- Java学习整理系列之Java反射机制
- Web页面取得当前日期
- JavaScript闭包讨论(一)
- Angularjs 指令示例
- "typeinfo for XXX::xxx", referenced from:typeinfo for xxx::xxx > in xx.o
- shell编程-正则表达式
- HttpComponent-HttpClient使用-发送Post请求
- 采用路径模型实现遍历二叉树的方法
- AS—':app:dexDebug'.
- 如何让hbox布局的界面自适应高度
- 在myeclipse中部署项目时nested exception is java.lang.OutOfMemoryError:
- tensorflow示例代码注释4
- APK 安装过程 及 原理 详解
- Java嵌套for循环-标签使用