grep命令和正则表达式(BRE)
wc -l passwd #c查看passwd行数
grep -v “root” passwd #找不是root的内容
grep -i “cat” abc.txt #不区分大小写找cat
grep “student” passwd #找有student的一行
grep -n “student” passwd #找并显示行号
grep -A -2 -n “student” passwd #先找到那一行再找其下面的两行
grep -B -2 -n “student” passwd #先找到那一行再找其上面的两行
grep -C -2 -n “student” passwd #先找到那一行再找其上下两行
grep -c “student” passwd #匹配到student的次数
grep -q “student” passwd
echo $? #为0则匹配到了,为1则没匹配到
grep -e “student” -e “operator” passwd #匹配有student或operator的行
基本正则表达式的元字符
grep “[root]” passwd #匹配包含r,o,t的字符
grep “[0-9]” passwd #匹配包含0到9的字符
grep “1[0-9]” passwd #匹配包含10,11,12······19的字符
grep “10{3}” passwd #匹配包含1000的字符
grep “x*y” abc.txt #匹配x出现任意次,包含y的字符,xayj就只匹配了y,和xa没关系
grep “x.*y” abc.txt #x和y之间可以有任意字符,而且多个也可以,但必须有x y
grep “x?y” abc.txt #匹配x出现0次或一次后面是y的字符
grep “x+y” abc.txt #x次数大于一次,y的字符
grep “x{2,5}” abc.txt #x出现2到5次的字符
grep “x{0,2}{,2}” abc.txt #匹配x至多出现两次的字符
扩展正则表达式
扩展表达式必须要加 -E ,而且加()括号
grep -E “(yab|ab)” abc.txt #匹配包含yab或ab的字符
grep -E -w “(yab|ab)” abc.txt 匹配ab或者yab ,而不是包含它,必须完整的单词