regular expression,REGEXP;
正常默认情况,grep 工作在贪婪模式,尽可能多的匹配。
.*:任意字符。
元字符:
.:匹配任意单个字符
[]:匹配指定范围内的任意单个字符。
[^]:匹配指定范围外的任意单个字符。
[:digit:]:数字匹配;[:lower:]:小写字母;[:upper:]大写字母;[:punct:]:符号
[:space:]:所有空格;[:alpha:]:所有字母;[:alnum:]所有数字字母;
eg:
[root@iZ233y80y23Z ~]# grep '[[:digit:]]$' /etc/inittab
# multi-user.target: analogous to runlevel 3
# graphical.target: analogous to runlevel 5
匹配次数:
*:匹配其前面的字符任意次;a*b:a出现任意次后面加上b;跟文件通配不同;注意;
\?:匹配其前面字符1次或者0次;需要转义字符\;grep 'a\?b' grep.txt
\+:匹配其前面字符出现至少一次。需要转义字符\;grep 'a\+b' grep.txt
\{m,n\}:匹配其前面字符出现该范围区间的。grep 'a\{1, 3\}b' grep.txt
位置锚定:
^:锚定行首,此字符后面的任意内容必须出现在行首。grep '^r..t' /etc/passwd
$:锚定行尾,此字符前面的任意内容必须出现在行尾。grep 'bash$' /etc/passwd
^$:空白行。# grep '^$' /etc/bashrc | wc -l
\<或者\b:其后面的任意字符必须作为单词首部出现。
\>或者\b:其前面的任意字符必须作为单词尾部出现。
\<root\>:root必须作为单词的首部或者尾部;
eg:
[root@iZ233y80y23Z test]# cat word.txt
this is root.
the user is mroot
rooter is a dog,s name
chroot is command
mrooter is dog
root is my dd
[root@iZ233y80y23Z test]# grep '\<root\>' word.txt
this is root.
root is my dd
eg:
[root@iZ233y80y23Z test]# cat grep.txt
a
b
ab
aab
acb
adb
amnb
grep 'a\?b' grep.txt
分组:\(\):在后面能引用到
\(ab\)*:ab这个分组可以出现零次一次或者N次;grep '\(ab\)*' grep.txt
后向引用:
\1:第一个左括号以及与之对应的右括号所包含的所有内容。# grep '\(l..e\).*\1' lover.txt
\2:第二个括号。
eg:
[root@iZ233y80y23Z test]# cat lover.txt
he love his lover
she like her lover
he like his liker
she love his lover