Linux 命令之grep

简介

grep 是一种强大的搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

grep 常用语法

[root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据
-c :计算找到 '搜寻字符串' 的次数
-i :忽略大小写的不同,所以大小写视为相同
-n :顺便输出行号
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
--color=auto :可以将找到的关键词部分加上颜色的显示喔!

将 /etc/passwd ,有出现 root 的行取出来

[root@VM_81_181_centos ~]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@VM_81_181_centos ~]# cat /etc/passwd | grep 'root'
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@VM_81_181_centos ~]# 

将 /etc/passwd 中 包含 root 的行取出来,并显示这些行在 /etc/passwd 中的行号

[root@VM_81_181_centos ~]# grep -n 'root' /etc/passwd 
1:root:x:0:0:root:/root:/bin/bash
11:operator:x:11:0:operator:/root:/sbin/nologin
[root@VM_81_181_centos ~]# 

将 /etc/passwd 中,没有出现 root 和 nologin 的行取出来

[root@VM_81_181_centos ~]# cat /etc/passwd | grep -v 'root' | grep -v 'nologin'
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
syslog:x:498:498::/home/syslog:/bin/false
centos:x:500:501:Cloud User:/home/centos:/bin/bash
xiaoming:x:501:502::/home/xiaoming:/bin/bash
xiaoyang:x:502:503::/home/xiaoyang:/bin/bash
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
[root@VM_81_181_centos ~]# 

根据文件内容递归查找目录

grep 'energywise' * # 在当前目录下查找带所要查找字符串的文件
grep -r 'energywise' * #在当前目录及其子目录下搜索"energywise"的文件
grep -l -r 'energywise' * #在当前目录及其子目录下搜索'energywise'行的文件,但是不显示匹配的行,只显示匹配的文件

这几个命令很实用,是查找文件的利器

猜你喜欢

转载自www.cnblogs.com/leeyongbard/p/9715414.html