grep 工具
- 语法grep [-cinvABC] 'word' filename
-c 行数 -i 不区分大小写 -n 显示行号 -v 取反,将除了其意外的过滤并显示出来 -r 遍历所有子目录 -A 后面跟数字,过滤出符合要求的行以及下面n行 -B 同上,过滤出符合要求的行以及上面n行 -C 同上,同时过滤出符合要求的行以及上下各n行
grep工具具体用法示例
- 概览
- 注:做实验时,一般吧文件复制到一个实验目录,不直接修改文件
特殊符号**^**:放在括号里面是取反,外面是以什么开头
例如 [^0-9] 那就是非数字(包括字母+特殊符号); 例如[^a-zA-Z] 那就是非字母(包括数字+特殊符号) 例如[^0-9a-zA-Z]那就是非数字字母(特殊符号)
grep -n 'root' /etc/passwdgrep -nv 'nologin' /etc/passwdgrep '[0-9]'/etc/inittabgrep -v '[0-9]'/etc/inittabgrep -v '^#' /etc/inittabgrep -v '^#' /etc/inittab|grep -v '^$'grep '^[^a-zA-Z]' test.txtgrep 'r.o' test.txt //.表示匹配任意字符grep 'oo*' test.txt //*表示匹配其左边0到n个重复的字符grep '.*' test.txt //.*表示匹配所有字符,包括空行grep 'o\{2\}' /etc/passwd //{}表示其前面字符的一个范围
- 示例1.
[root@centos001 grep]# grep '[0-9]' passwd root:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologin[root@centos001 grep]# grep -v '[0-9]' passwd [root@centos001 grep]#
- 示例2.过滤是否带有#号的文件,
[root@centos001 grep]# grep -n '^#' inittab //查看带有#的1:# inittab is no longer used when using systemd.[root@centos001 grep]# grep -nv '^#' inittab //查看没有#号的9:kJAHkladh
- 示例3.特殊符号^
[root@centos001 grep]# grep '[^0-9]' inittab //过滤并列出除了数字的字符# inittab is no longer used when using systemd.[root@centos001 grep]# grep '^[^0-9]' inittab //过滤并列出除了数字开头的字符# inittab is no longer used when using systemd.[root@centos001 grep]# grep -nv '^[^0-9]' inittab //过滤并列出与上面相反的内容8:123123421
- 示例4.使用.*匹配指定字符串
[root@centos001 grep]# grep 'r.o' passwd //这个点代表任意字符root:x:0:0:root:/root:/bin/bash[root@centos001 grep]# grep 'aming.*bash' passwd //在。*首位输入字符串的首尾名称aming:x:1001:1007::/home/aming:/bin/bash
egrep
- 介绍:egrep为grep的扩展版本
- 概览
grep 'o\{2\}' /etc/passwd //指定要过滤字符的出现字数 注:这个必须加上转义字符\ egrep 'o{2}' /etc/passwd //egrep可不用加\ egrep 'o+' /etc/passwd //过滤一个或多个指定的字符,匹配一个或多个+号前面的字符 egrep 'oo?' /etc/passwd //过滤0个或一个指定字符,?前的字符为0或1 egrep 'root|nologin' /etc/passwd //竖线表示或者的意思 egrep '(oo){2}' /etc/passwd
- 示例:特殊符号+,过滤一个或多个指定字符
[root@centos001 grep]# grep 'o+a' passwd //这里能看到grep是不能和+号一起使用的[root@centos001 grep]# egrep 'o+m' passwd // 指定过滤user1:x:1000:1000::/home/user1:/bin/bash
扩展
- 把一个目录下,过滤所有*.php文档中含有eval的行
grep -r --include="*.php" 'eval' /data/