grep命令 - 强大的文本搜索工具
grep是用于全面搜索的正则表达式,并将结果输出。人们通常会将grep命令与正则表达式搭配使用,参数作为搜索过程中的补充或对输出结果的筛选,命令模式十分灵活
与之容易混淆的是egrep命令和fgrep命令。如果把grep命令当做是标准搜索命令,那么egrep则是扩展搜索命令,等价于“grep -E”命令,支持扩展的正则表达式。而fgrep则是快速搜索命令,等价于“grep -F”命令,不支持正则表达式,直接按照字符串内容进行匹配
语法格式: grep [参数] 文件名
常用参数
-b | 显示匹配行距文件头部的偏移量 |
-c | 只显示匹配的行数 |
-E | 支持扩展正则表达式 |
-F | 匹配固定字符串的内容 |
-h | 搜索多文件时不显示文件名 |
-i | 忽略关键词大小写 |
-l | 只显示符合匹配条件的文件名 |
-n | 显示所有匹配及其行号 |
-o | 显示匹配词距文件头部偏移量 |
-q | 静默执行模式 |
-r | 递归搜索模式 |
-s | 不显示没有匹配文本的错误信息 |
-v | 显示不包含匹配文本的所有行 |
-w | 精准匹配整词 |
-x | 精准匹配整行 |
参考示例
搜索某个关键词的内容行
[root@localhost etc]# grep root passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
搜索以关键词开头的行
[root@localhost etc]# grep ^root passwd
root:x:0:0:root:/root:/bin/bash
搜索多个文件中包含某个关键词的行
[root@localhost etc]# grep root /etc/passwd /etc/shadow
/etc/passwd:root:x:0:0:root:/root:/bin/bash
/etc/passwd:operator:x:11:0:operator:/root:/sbin/nologin
/etc/shadow:root:$6$XANT6cRDzHm1.yDF$b1jummJ6.R1vG/sH4y1VRRuELpImFx2VAbO70HhcwEgGq8tFxkd983SzY8NaD.Ol5HsJCPlG8s4lmqB2jBYJl0::0:99999:7:::
搜索多个文件中包含某个关键词的行,不显示文件名
[root@localhost etc]# grep -h root /etc/passwd /etc/shadow
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
root:$6$XANT6cRDzHm1.yDF$b1jummJ6.R1vG/sH4y1VRRuELpImFx2VAbO70HhcwEgGq8tFxkd983SzY8NaD.Ol5HsJCPlG8s4lmqB2jBYJl0::0:99999:7:::
显示指定文件中包含某个关键词行的数量
[root@localhost etc]# grep -c root /etc/passwd /etc/shadow
/etc/passwd:2
/etc/shadow:1
搜索指定文件中包含某个关键词位置的行号及内容行
[root@localhost etc]# grep -n root /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
10:operator:x:11:0:operator:/root:/sbin/nologin
搜索指定文件中不包含某个关键词的内容行
[root@localhost etc]# grep -v nologin /etc/passwd
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
搜索目录中包含某个关键词内容的文件,未找到则提示
[root@localhost etc]# grep -l root /etc/*
/etc/aliases
grep: /etc/alternatives: 是一个目录
/etc/anacrontab
grep: /etc/audit: 是一个目录
grep: /etc/authselect: 是一个目录
grep: /etc/bash_completion.d: 是一个目录
grep: /etc/binfmt.d: 是一个目录
grep: /etc/chkconfig.d: 是一个目录
搜索当目录中包含某个关键词内容的文件,未找到不提示
[root@localhost etc]# grep -ls root /etc/*
/etc/aliases
/etc/anacrontab
/etc/crontab
/etc/fstab
/etc/group
/etc/group-
/etc/grub2.cfg
/etc/gshadow
/etc/gshadow-
/etc/kdump.conf
/etc/mtab
/etc/passwd
/etc/passwd-
/etc/services
/etc/shadow
/etc/shadow-
/etc/sudoers
不仅搜索指定目录,还搜索其内子目录内是否有关键词文件:
[root@localhost etc]# grep -slr /etc/
fstab
libssh/libssh_client.config
libssh/libssh_server.config
security/chroot.conf
security/console.handlers
security/console.perms
security/faillock.conf
security/group.conf
security/limits.conf
搜索指定文件中空行的数量
[root@localhost ~]# grep -c ^$ anaconda-ks.cfg
13