1.
*表示匹配前一个字符0个或多个
[root@study ~]# echo -e "xoaa"|grep "xo*"
xoaa
[root@study ~]# echo -e "xaa"|grep "xo*"
xaa
2.
shell正则表达式分两种:基础正则表达式BRE(basic regular express)和扩展正则表达式ERE(extend regular express),扩展的表达式有+、?、|、和()
[root@study ~]# echo -e "abc\nabcc\nadd"|grep -E "ab+"
abc
abcc
grep -o 只打印出匹配到的字符 -n打印行号
#匹配单个数字
[root@study ~]# echo "ad12234b32c" |grep -o '[0-9]'
1
2
2
3
4
3
2
#连续匹配多个数字
[root@study ~]# echo "ad12234b32c" |grep -oE '[0-9]+'
12234
32
匹配前面字符1个或0个
[root@study ~]# echo -e "ac\nabc\nadd"|grep -E 'a?c'
ac
abc
匹配末尾数字
[root@study ~]# echo "abc;cde;1234"|grep -E '[^;]+$'
abc;cde;1234
#运行上面命令后,1234标红
<匹配字符串开始 >匹配字符串结束,使用中应该加反斜杠 \< \>,作用与^$一样
[root@study ~]# echo -e "1\n12\n123\n21234"|grep '\<12'
12
123
()单元或组合:将小括号里面作为一个组合
[root@study ~]# echo "123abc"|grep -E -o '([0-9a-z]){4}'
123a
()分组:匹配小括号中正则表达式或字符。\n反向引用,n是数字,从1开始编号,表示引用第n个分组匹配的内容
[root@study ~]# echo "1123abc"|grep -E -o '(1)\1'
11
3.
Posix字符
[root@study ~]# echo "1123abc"|grep -o '[:lower:]'
grep: 字符类的语法是 [[:space:]],而非 [:space:]
[root@study ~]# echo "1123abc"|grep -o '[[:alnum:]]'
1
1
2
3
a
b
c
[root@study ~]# echo "1123abc"|grep -o '[[:alpha:]]'
a
b
c
[root@study ~]# echo "1123abc"|grep -o '[[:lower:]]'
a
b
c
[root@study ~]# echo "1123abcZ"|grep -o '[[:upper:]]'
Z
[root@study ~]# echo "1123abcZ"|grep -o '[[:digit:]]'
1
1
2
3
[root@study ~]# echo "1123abcZ"|grep -oE '[[:digit:]]{4}'
1123
[root@study ~]# echo "1123abcZ"|grep -oE '[[:space:]]'
[root@study ~]# echo "1123abcZ \t"|grep -oE '[[:space:]]'
[root@study ~]# echo -e "\n1123abcZ \t"|grep -oE '[[:space:]]'
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -oE '[[:space:]]'
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -E '[[:space:]]'
1123abcZ
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -oE '[[:graph:]]'
1
1
2
3
a
b
c
Z
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -oE '[[:blank:]]'
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -oE '[[:blank:]]' -v
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -voE '[[:blank:]]'
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -vE '[[:blank:]]'
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -o '[[:cntrl:]]'
[root@study ~]# echo -e "\n1123abcZ \n\t \t"|grep -o '[[:print:]]'
1
1
2
3
a
b
c
Z
[root@study ~]# echo -e "\n1123abcZ[' \n\t \t,"|grep -o '[[:punct:]]'
[
'
,
[root@study ~]# echo -e "\n1123abcZ[' \n\t \t,;"|grep -o '[[:punct:]]'
[
'
,
;
[root@study ~]# echo -e "\n1123abcZ[' \n\t \t,;0x10"|grep -o '[[:xdigit:]]'
1
1
2
3
a
b
c
0
1
0
4.
grep 默认不支持扩展表达式,加-E选项开启ERE。如果不加-E使用花括号要加转义符\{\}
egrep 支持基础和扩展表达式
awk 支持egrep所有的正则表达式
sed 默认不支持扩展表达式,加-r选项开启ERE。如果不加-r使用花括号要加转义符\{\}
5.