正则表达式:REGEXP,REGular EXPression。 正则表达式分为两类:
Basic REGEXP(基本正则表达式)Extended REGEXP(扩展正则表达式)元字符
. 任意单个字符 [root@linux131 ~]# grep 'ignore....' anaconda-ks.cfg ignoredisk --only-use=nvme0n1 [root@linux131 ~]# grep 'i........k' anaconda-ks.cfg ignoredisk --only-use=nvme0n1 [] 匹配指定范围内的任意单个字符 [root@linux131 ~]# touch {1..100} [root@linux131 ~]# ls|grep '^[0-9]$' //个人数 1 2 3 4 5 6 7 8 9 [root@linux131 ~]# ls|grep '^[0-9][0-9]$' //双位数 10 11 12 略... 97 98 99 [root@linux131 ~]# ls|grep '^[0-9][0-9][0-9]$' //三位数 100 [^] 匹配指定范围外的任意单个字符(取反) [root@linux131 ~]# ls 1 16 23 30 38 45 52 6 67 74 81 89 96 10 17 24 31 39 46 53 60 68 75 82 9 97 100 18 25 32 4 47 54 61 69 76 83 90 98 11 19 26 33 40 48 55 62 7 77 84 91 99 12 2 27 34 41 49 56 63 70 78 85 92 13 20 28 35 42 5 57 64 71 79 86 93 anaconda-ks.cfg 14 21 29 36 43 50 58 65 72 8 87 94 15 22 3 37 44 51 59 66 73 80 88 95 [root@linux131 ~]# ls|grep '[^0-9]' //显示除了括号里的东西 anaconda-ks.cfg匹配次数(贪婪模式)
*匹配其前面的任意单个字符任意次 [root@linux131 ~]# ls|grep '^5*$' 5 55 [root@linux131 ~]# ls|grep '^10*$' 1 10 100 .* 任意长度的任意字符 [root@linux131 ~]# ls|grep '.*' //代表所有 1 10 100 11 12 13 略... \? 匹配其前面的任意单个字符1次或0次 [root@linux131 ~]# ls|grep '^10\?' 1 10 100 11 12 13 14 15 16 17 18 19 \+ 匹配其前面的任意单个字符至少1次 [root@linux131 ~]# ls|grep '^12\+$' 12 [root@linux131 ~]# ls|grep '^18\+$' 18 188 1888 \ {m,n\} 匹配其前面的任意单个字符至少m次,至多n次 [root@linux131 ~]# ls|grep '^18\{2,4\}$' 188 1888 [root@linux131 ~]# ls|grep '^1\{1,4\}$' 1 11 111 1111 [root@linux131 ~]# ls|grep '^100\{5,6\}100$' 100000100 1000000100位置锚定
^ 锚定行首,此字符后面的任意单个字符必须出现在行首 [root@linux131 ~]# ls|grep '^2' 2 20 21 22 23 24 25 26 27 28 29 $ 锚定行尾,此字符前面的任意单个字符必须出现在行尾 [root@linux131 ~]# ls|grep '9$' 19 29 39 49 59 69 79 89 9 99 ^$ 空白行 [root@linux131 ~]# cat 11 //写个文件内容有三行空格 dfjhj gkhfj kdjfhkf dfljd [root@linux131 ~]# grep '^$' 11 //取出空格有三行 [root@linux131 ~]#\<或\b 锚定词首,其后面的任意单个字符必须作为单词首部出现
\>或\b 锚定词尾,其前面的任意单个字符必须作为单词尾部出现
[root@linux131 ~]# ls |grep '\<19\>' 19 [root@linux131 ~]# ls |grep '\b19\b' 19分组
\(\) 例:\(ab\)* //后向引用 \1 //引用第一个左括号以及与之对应的右括号所包括的所有内容 \2 //引用第二个左括号以及与之对应的右括号所包括的所有内容例子:
[root@linux131 ~]# ls|grep '^\(12\|100\)\+$' 100 100100 100100100 100100100100 12 1212 121212 [root@linux131 ~]# ls|grep '^\(12\|100\)\?$' 100 12