1.grep家族
- grep:在文件中全局查找指定的正则表达式,并打印所有包含该表达式的行
- egrep:扩展的egrep,支持更多的正则表达式元字符
- fgrep:固定grep(fixed grep),,有时候也被称之为快速fast grep,它按字面解释所有的字符
2.grep和egrep使用的元字符
- grep -q选项:不输出结果
- grep [选项] PATTERN filename 。。。
grep 'Tom' /etc/passwd
找到:grep的退出状态为0
找不到:grep的退出状态为1
找不到指定文件:grep的退出状态为2
- grep程序的输入可以来自标准输入或者管道,而不仅仅是文件
ps aux|grep 'sshd'
-
grep:使用基本元字符集^,$,.,*,[],[ ^ ],\ < \ >,\ ( \ ),\ { \ },\ +,\ |
*表示前导符,[]表示括号里面任意一个,\ < \ >表示词首词尾,\ ( \ )表示标签或者字符组,\ { \ }表示匹配n次 -
egrep(或者grep -E):使用扩展元字符集?,+,{},|,()
(1)注意:grep也可以使用扩展集中的元字符,仅需要对这些元字符前置一个反斜线
(2)\w 所有字母与数字,称之为字符[a-zA-Z0-9],‘l[a-zA-Z0-9]ove’,‘l\wove’
(3)\W 所有字母与数字之外的字符,称之为非字符,‘love[^a-zA-Z0-9]+’,‘love\W’ -
eg:
grep -E 或者egrep
egrep 'NW' datafile 找有NW的行
egrep 'NW' d* 找以d开始的所有文件
egrep '^n' datafile 找以n开始的行
egrep '4$' datafile 找以4结尾的行
egrep TB Savage datafile 找TB
egrep 'TB Savage' datafile 找TB Savage
egrep '5\..' datafile 找5.任意一个字符
egrep '\.5' datafile 找.5的行
egrep '^[we]' datafile 找we开头的行
egrep '[^0-9]' datafile 找非数字行
egrep '[A-Z][A-Z] [A-Z]' datafile 找大写字母大写字母空格大写字母的行
egrep 'ss*' datafile 找至少一个s egrep 's+' datafile
egrep '[a-z]{9}' datafile 找连续出现9个相同英文字母
egrep '\<north' datafile 找north词首
egrep '\<north\>' datafile 找north单词
egrep '\<[a-r].*n\>' datafile 找a-r开头,n结尾的单词
egrep '\^n\w*\W' datafile 以n开头的字符,跟着非字符
egrep '\bnorth\b' datafile 找north单词
egrep 'NW|EA' datafile 找NW或EA的行
egrep '3+' datafile 找1到多个3的行
egrep '2\.?[0-9]' datafile 找2零到1个点,接着数字
egrep '(no)+' datafile 找no出现1到n次
egrep 'S(h|u)' datafile Sh或Su
egrep 'Sh|u' datafile Sh或u
3.grep选项
- eg:
grep --help|grep '\-v' ##-v这里是选项
grep -R '=~' /root/ 目录
grep '=~' /root/* 文件
颜色的话,在vim .bashrc中添加:
alias grep='grep --color'
grep -B2 'root' /etc/passwd 还包括root的行的前两行
grep -A2 'root' /etc/passwd 还包括root的行的后两行
grep -C2 'root' /etc/passwd 还包括root的行的前两行和后两行