Linux命令篇-grep命令

博客 动态
0 204
羽尘
羽尘 2022-05-03 01:58:42
悬赏:0 积分 收藏

Linux命令篇 - grep 命令

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/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
  • 在管道中使用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 allyum makecacheyum install -y epel-release.noarchyum clean allyum makecacheyum 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.outreposinstall.sh
  • 搜索多个字符串(不使用 -E)
# 需要使用\转义|$ grep "yum\|aliyun\|bar" *.sh
  • 排除特定的字符
# 使用-v选项忽略搜索。下面的命令将在除“syslog.log”之外的所有文件中搜索字符串“error”$ grep -r error * | grep -v ‘/\syslog.log/’

posted @ 2022-05-03 01:33 HOsystem 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    羽尘

    羽尘 (王者 段位)

    2335 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员