shell 正则表达式

正则表达式:(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]' test
4、查找不以r开头的行
5、查找以数字开头的行
6、查找以大写字母开头的
7、查找以小写字母开头的
8、查找以点.结尾的
9、去掉空行
10、完全匹配hello的行
11、查找A后有三个数字的行
# grep 'A[0-9]\{3,\}' test
# grep -E 'A[0-9]{3,}' test
12、统计root在/etc/passwd里出现的次数
# grep -o root /etc/passwd|wc -l
13、用正则表达式找出自己的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.1
10.1.1.255
255.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.1
10.1.1.255
255.255.255.0

14、找出文件中的ip地址并打印替换成172.16.2.254
sed -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' test
15、找出文件中的ip地址
# grep -o -P '\d+\.\d+\.\d+\.\d+' test
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值