我的新浪微博:http://weibo.com/u/1602714773
CSDN博客:http://blog.csdn.net/hunterno4
Linux Shell笔记之正则表达式
上一篇 /
下一篇 2013-11-30 16:54:44
/ 个人分类:Linux
Linux中,两种流行的正则表达式引擎1.POSIX基本正则表达式(BRE)引擎2.POSIX扩展正则表达式(ERE)引擎sed编辑器只实施了BRE引擎规范的子集gawk程序使用ERE引擎一、基本正则表达式BRE
1.纯文本# echo "This is a test"| sed -n '/this/p' //区分大小写# echo "This is a test"| sed -n '/ /p' //可以匹配空格This is a test2.特殊字符.*[]^${}\+?|()要匹配这些特殊字符需要转义# echo "This is a $ test"| sed -n '/\$/p' //实践表明貌似$+等并不需要转义This is a $ test# echo "This is a / test"| sed -n '/\//p' //'/'符号也需转义This is a / test3.锚字符1)锁定在行首脱字符^锁定在行首# echo "the book test"| sed -n '/^book/p' //book需要在行首才匹配2)锁定在行尾美元符$锁定在行尾# echo "the book test"| sed -n '/book$/p' //book需要在行尾才匹配# echo "the book test"| sed -n '/test$/p'the book test3)组合锚点# cat dataempty this is line onethis is line two# sed '/^$/d' dataempty //^$组合匹配空白行,然后使用d命令删除空白行this is line onethis is line two4.点字符点击特殊字符匹配任意的单字符5.字符组使用方括号匹配字符组# echo "Yes" | sed -n '/[Yy]es/p'Yes# echo "yes" | sed -n '/[Yy]es/p'yes6.排除字符组在字符组的开头加个脱字符]# cat dataatthis is a testthis is at line twothis is catthis is hatat ten]# sed -n '/[^ch]at/p' dataat //加^符号,不输出匹配cat与hatthis is at line two7.使用区间使用单破折号在字符组中使用字符区间# echo "a7689" | sed -n '/^[0-9][0-9][0-9][0-9][0-9]$/p'8.特殊字符组[[:alpha:]] 匹配任意字母字符[[:digit:]] 匹配0-9之间的数字[[:lower:]] 匹配小写字母[[:upper:]] 匹配大写字母9.星号*号说明该字符会在匹配模式的文本中出现0次或多次.*组合,匹配任意多个任意字符二、扩展正则表达式ERE
1.问号?号表明前面的字符可以出现0次或1次2.加号+号表明前面的字符可以出现1次或多次,但必须至少出现1次# echo "bat" | gawk '/b[ae]+t/{print $0}'bat3.花括号{m}正则表达式准确出现m次{m,n}正则表达式至少出现m次,至多出现n次# echo "baat" | gawk --re-interval '/ba{1}t/{print $0}' //gawk中需指定--re-interval才能识别花括号区间# echo "bat" | gawk --re-interval '/ba{1}t/{print $0}'bat4.管道符号# echo "this is a cat" | gawk '/cat|dog/{print $0}' //逻辑OR方式,匹配cat或dogthis is a cat5.聚合表达式用()括号聚合起来,一串字符可以当作一个字符一样来匹配# echo "Sat" | gawk '/Sat(urday)?/{print $0}'Sat# echo "Saturday" | gawk '/Sat(urday)?/{print $0}'Saturday三、实用例子
1.目录文件计数#!/bin/bashmypath=`echo $PATH | sed 's/:/ /g'` //将PATH中的:用空格替换count=0for directory in $mypathdo check=`ls $directory` for item in $check do count=$[ $count + 1 ] done echo "$directory - $count" count=0done# ./countfiles /usr/local/program/jdk1.6.0_33/bin - 44/usr/kerberos/sbin - 12/usr/kerberos/bin - 20
收藏
举报
TAG:
gawk
Linux
linux
正则表达式
sed
shell
Shell