shell 正则表达式

来源:互联网 发布:大麦户源码下载 编辑:程序博客网 时间:2024/05/01 21:35
正则表达式:(Regular Expression regex regexp)find vim locate grep sed awk第一类正则:前导字符,(位于元字符前面的字符);元字符:在正则里有特殊的专用的含义的符号. :除了换行符以外的任意单个字符* :bo* bo|boo.* :^:$:^$:[]:[^]:^[]:^[^]:\<:\>:\<\>:\{n\} {n}: \{n,\} {n,}:\{n,m\} {n,m}:\(\) 扩展正则:grep -E|egrep 1111  grep 'root|sync' /etc/passwd 1112  grep -E 'root|sync' /etc/passwd 1113  egrep 'root|sync' /etc/passwd+: bo+ bo boo 前导字符连续出现1次或者多次?:前导字符连续出现0次或者11117  grep -E 'g+' test1 1118  grep 'g+' test1 1119  egrep 'g+' test1 1120  grep -E 'g+o?' test1 1121  grep -E 'go?' test1\d [0-9]\w 匹配数字字母和下划线\s 匹配空格、制表符、换页符、换行符(\t\r\n) 1129  grep -P '\d' test 1130  grep -P '\w' test 1131  vim test 1132  grep -P '\s' test第二类正则:# grep '[[:alnum:]]' test       [[:alnum:]]              all letters and digits       [[:alpha:]]              all letters       [[:blank:]]              all horizontal whitespace       [[:cntrl:]]              all control characters       [[:digit:]]              all digits       [[:graph:]]              all printable characters, not including space       [[:lower:]]              all lower case letters       [[:print:]]              all printable characters, including space       [[:punct:]]              all punctuation characters       [[:space:]]              all horizontal or vertical whitespace       [[:upper:]]              all upper case letters课堂练习:1、查找不以大写字母开头的行(3种写法)^[^A-Z][[:upper:]]-v '^[A-Z]'2、查找有数字的行(2种)3、查找一个数字和一个字母连起来的行[0-9][a-Z]|[a-Z][0-9]# grep -E '[0-9][a-Z]|[a-Z][0-9]' test4、查找不以r开头的行5、查找以数字开头的行6、查找以大写字母开头的7、查找以小写字母开头的8、查找以点.结尾的9、去掉空行10、完全匹配hello的行11、查找A后有三个数字的行# grep 'A[0-9]\{3,\}' test# grep -E 'A[0-9]{3,}' test12、统计root在/etc/passwd里出现的次数# grep -o root /etc/passwd|wc -l13、用正则表达式找出自己的IP地址、广播地址、子网掩码(一条命令搞定)[root@node1 shell03]# ifconfig eth0|grep Bcast|grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'10.1.1.110.1.1.255255.255.255.0[root@node1 shell03]# ifconfig eth0|grep Bcast          inet addr:10.1.1.1  Bcast:10.1.1.255  Mask:255.255.255.0[root@node1 shell03]# ifconfig eth0|grep Bcast|grep -o -P '\d+\.\d+\.\d+\.\d+'10.1.1.110.1.1.255255.255.255.014、找出文件中的ip地址并打印替换成172.16.2.254sed -n 's/xxx/xxx/p' filename# sed -n 's/\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.\)110/\1254/p' test# sed -n 's/\(172\.16\.2\.\)110/\1254/p' test15、找出文件中的ip地址# grep -o -P '\d+\.\d+\.\d+\.\d+' test
0 0
原创粉丝点击