grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
grep:用于全面搜索的正则表达式,并将结果输出;
格式:
egrep则是扩展搜索命令,等价于“grep -E”命令,支持扩展的正则表达式。而fgrep则是快速搜索命令,等价于“grep -F”命令,不支持正则表达式,直接按照字符串内容进行匹配;
常用参数:
| -i | 忽略大小写 |
|---|---|
| -c | 只输出匹配行的数量 |
| -l | 只列出符合匹配的文件名,不列出具体的匹配行 |
| -n | 列出所有的匹配行,显示行号 |
| -h | 查询多文件时不显示文件名 |
| -s | 不显示不存在、没有匹配文本的错误信息 |
| -v | 显示不包含匹配文本的所有行 |
| -w | 匹配整词 |
| -x | 匹配整行 |
| -r | 递归搜索 |
| -q | 禁止输出任何结果,已退出状态表示搜索是否成功 |
| -b | 打印匹配行距文件头部的偏移量,以字节为单位 |
| -o | 与-b结合使用,打印匹配的词据文件头部的偏移量,以字节为单位 |
| -F | 匹配固定字符串的内容 |
| -E | 支持扩展的正则表达式 |
参考案例:
$ grep "root" /etc/passwdroot:x:0:0:root:/root:/bin/bashoperator:x:11:0:operator:/root:/sbin/nologin$ grep "root" /etc/passwd /etc/group/etc/passwd:root:x:0:0:root:/root:/bin/bash/etc/passwd:operator:x:11:0:operator:/root:/sbin/nologin/etc/group:root:x:0:# 使用 -i 忽略大小写$ grep -i HAL /etc/passwdhalt:x:7:0:halt:/sbin:/sbin/halthaldaemon:x:68:68:HAL daemon:/:/sbin/nologin# 递归搜索使用 -i# If you want to include symlinks use -R.$ grep -r nginx /var# ls -R / : 递归显示ls# grep backup: 输出文件命名中包含backup# 单个grep$ ls -R / |grep backup# 多个grep$ ps -ef | grep docker | grep apache# 搜索以yum为开头的行$ grep "^yum" /opt/reposinstall.sh yum clean allyum makecacheyum install -y epel-release.noarchyum clean allyum makecacheyum repolist all# -w : 使用参数-w匹配完整的词$ grep -iw "aliyun" /etc/yum.repos.d/CentOS-Base.repo# -A选项,在匹配的字符串后显示N行$ grep -A 1 "root" /etc/passwd# -B选项,在匹配的字符串前显示N行$ grep -B 1 "root" /etc/passwd# -E : 使用正则表达式过滤内容# -w : 匹配整个词$ ls | grep -w -E "a|reposinstall"a.outreposinstall.sh# 需要使用\转义|$ grep "yum\|aliyun\|bar" *.sh# 使用-v选项忽略搜索。下面的命令将在除“syslog.log”之外的所有文件中搜索字符串“error”$ grep -r error * | grep -v ‘/\syslog.log/’