ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Linux命令篇 - grep 命令

2022-05-03 02:02:22  阅读:154  来源: 互联网

标签:搜索 grep etc 命令 yum Linux 匹配 root


grep

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:用于全面搜索的正则表达式,并将结果输出;

格式

  • grep [OPTIONS] PATTERN [FILE...]
  • grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]

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/passwd
root:x:0:0:root:/root:/bin/bash
operator: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/passwd
halt:x:7:0:halt:/sbin:/sbin/halt
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
  • 递归搜索
# 递归搜索使用 -i
# If you want to include symlinks use -R.
$ grep -r nginx /var
  • 在管道中使用grep过滤
# 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 all
yum makecache
yum install -y epel-release.noarch
yum clean all
yum makecache
yum repolist all
  • 匹配完整词
# -w : 使用参数-w匹配完整的词
$ grep -iw "aliyun" /etc/yum.repos.d/CentOS-Base.repo
  • 显示匹配后的N行
# -A选项,在匹配的字符串后显示N行
$ grep -A 1 "root" /etc/passwd
  • 显示匹配前的N行
# -B选项,在匹配的字符串前显示N行
$ grep -B 1 "root" /etc/passwd
  • 搜索多个字符串(使用 -E)
# -E : 使用正则表达式过滤内容
# -w : 匹配整个词
$ ls | grep -w -E "a|reposinstall"
a.out
reposinstall.sh
  • 搜索多个字符串(不使用 -E)
# 需要使用\转义|
$ grep "yum\|aliyun\|bar" *.sh
  • 排除特定的字符
# 使用-v选项忽略搜索。下面的命令将在除“syslog.log”之外的所有文件中搜索字符串“error”
$ grep -r error * | grep -v ‘/\syslog.log/’

标签:搜索,grep,etc,命令,yum,Linux,匹配,root
来源: https://www.cnblogs.com/HOsystem/p/16217517.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有