1. Common options:
-E :开启扩展(Extend)的正则表达式。
-i :忽略大小写(ignore case)。
-v :反过来(invert),只打印没有匹配的,而匹配的反而不打印。
-n :显示行号
-w :被匹配的文本只能是单词,而不能是单词中的某一部分,如文本中有liker,而我搜寻的只是like,就可以使用-w选项来避免匹配liker
-c :显示总共有多少行被匹配到了,而不是显示被匹配到的内容,注意如果同时使用-cv选项是显示有多少行没有被匹配到。
-o :只显示被模式匹配到的字符串。
--color :将匹配到的内容以颜色高亮显示。
-A n:显示匹配到的字符串所在的行及其后n行,after
-B n:显示匹配到的字符串所在的行及其前n行,before
-C n:显示匹配到的字符串所在的行及其前后各n行,context
2. The common expression argument
\btom\b //“\b"中间tom代表是一个单词
\d 表示一个数字
\d{2}-\d{8}。 这里\d后面的{2}({8})的意思是前面\d必须连续重复匹配2次(8次)。
\s匹配任意的空白符,包括空格,制表符(Tab),换行符,中文全角空格等。
\w匹配字母或数字或下划线或汉字等。
. 匹配除换行符以外的任意字符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始 //^和$匹配的是行
$ 匹配字符串的结束
^\d{5,12}$ //填写的QQ号必须为5位到12位数字
备注:"\d"等这些字符只有在perl{正则支持的相对完整} 中能够使用
转义):
\字符
重复):
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
123.txt CAT | grep '\ BNO \ b'
# \ b Mouding ending or beginning of a word, the above represents only match no characters, one more will not
CAT 123.txt | '. grep ^ root 400 $'
# ^ Mouding beginning of the line , $ Mouding end of the line, which matches to 400 at the end of the line beginning with root
echo "111 222 333" | grep -o 1. 2
# to show only matching words
CAT / etc / the passwd | grep -n -A. 1 '. ^ root *'
# show root line and the next line, and the line number
Matching digital
echo "123abcABC" | grep -o ' [0-9]'
echo "2002 1945 1644 1892 1946" | grep -P '\ B (20 | 19) [0-9] {2} \ B'
# after the opening 20 represented by two characters or numbers 19, meaning {2} in front [0-9] must match twice, at least to match the 4 digits, but two \ b Mouding words beginning and end so that only 4 digits
Advanced Usage
echo " http://www.ylc520.com/"|grep -OP '+. (=:? //)'
# output http, expressed as: // as the delimitation forward match, + indicates. any character appear once or more
echo " http://www.ylc520.com/"|grep -OP '. (<=:? //) +'
# output www.ylc520.com/, expressed as: / / next match for the delimitation. + represents any character appears once or more
echo " http://www.ylc520.com/"|grep -OP '(? <= the WWW.). (? =. COM ) '
# output ylc520 expressed www. backward matching is delimited, while as .com forward delimitation matches. matches any character of any length