8.正则表达
echo “”:只有$,``,\有特殊含义
echo ‘’:纯字符串
echo -e “”:\t \n 之类的才有用
echo -e ‘’: -e:\t \n \\ 之类的才有用
grep
- -n:显示匹配成功的行号
- -o:只显示匹配成功的字符,
- -v:取反,除了匹配的显示
- -E:支持扩展正则等同于egrep
- -w:精准匹配,前后不多不少
- -i:不区分大小写
- -r:递归过滤目录及目录下所有内存
- -A:显示匹配到过滤内容后面n行
- -B:显示匹配到过滤内容前面n行
- -C:显示匹配到过滤内容前后各n行
- -c:统计某个单词出现的次数
基础正则
注:当做一个字符一个字符的作用域来看,不要整体来看这些的作用可能会更好一些
^
$
^$
1 2 3 4 5
| grep '^$' test.txt
grep -v -e '^$' -e '^#' /etc/selinux/config egrep -v '^#|^$' /etc/selinux/config
|
.
1
| grep '.E' /etc/selinux/config
|
*
.*
1 2 3
| grep '^.*c' grep 'c.*$'
|
[]
1 2 3
| # 单个字符范围 # []内的除^无特殊含义。例如.就是. grep 'a[a-z]' test.txt # a{a..z}匹配
|
{}
- {n,m}:前一个字符至少连续出现n次,最多出现m次
1
| egrep 'c{2,3}' # c这个字符最少出现2次,最多出现3次,贪婪匹配,有最多就匹配最多
|
扩展正则
使用扩展正则需要grep -E或egrep
+
|
1
| egrep ‘cat|test| test.txt
|
()
表示一个整体
1
| egrep ’ab(c|e)g' test.txt # 匹配abcg或abeg
|
eg
1
| cat /etc/passwd|tr ":" “ ”
|
1 2 3
| ifconfig ens33 ifup ens33 ifdown ens33
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| cat << eof test1 test2 eof
cat >> test.txt << test oiiiaoiiia oi test
cat << 'eof' <html> <head> <title> The title of your page $test </title> </head>
<body> Your page content goes here. </body> </html> eof
|
统计/etc/passwd字母出现次数
1
| cat /etc/passwd|tr ":/0-9x " " "|grep -o .|sort |uniq -c|sort -rn|grep -v ' $'
|