shell编程教学(三)| Linux三剑客之grep

怼烎@ 2022-03-12 09:46 400阅读 0赞

grep简介

grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用特定模式匹配(包括正则表达式)搜索文本,并默认输出匹配行。

一、grep的常见用法

  1. grep root passwd >> 显示 包含root 的行
  2. grep ^root passwd >> 显示 root开头 的行
  3. grep root$ passwd >> 显示 root结尾 的行
  4. grep -i root passwd >> -i表示忽略大小写
  5. grep -v root passwd >> 显示不包含root(匹配文本)的所有行
  6. grep -E "^root|bash$" passwd >> -E表示扩展的正则表达式,以root开头或者以bash结尾的行

注意:正规的 grep 不支持扩展的正则表达式 , 竖线是用于表示”或”的扩展正则表达式元字符 , 正规的 grep 无法识别,egrep 命令等同于‘grep -E
在这里插入图片描述

小试牛刀
在/mnt下的passwd中找出root位于中间的行
在这里插入图片描述

二、grep的正则表达式

  1. [root@allen mnt]# grep 'r..t' Grep_Test >> 表示匹配含从rt间有两个字符的行
  2. [root@allen mnt]# grep 'r*t' Grep_Test >> 表示匹配含从rt间有任意个字符的行
  3. [root@allen mnt]# grep 'ro*t' Grep_Test >> 表示匹配含从rt间有任意个o的行

如有什么不理解,请看截图中的变化
在这里插入图片描述

  1. [root@allen mnt]# grep -E 'ri{1,}t' Grep_Test >> 表示匹配含从rt间有1到无穷个 i 的行
  2. [root@allen mnt]# grep -E 'ri{1,2}t' Grep_Test >> 表示匹配含从rt间有12 i 的行
  3. [root@allen mnt]# grep -E 'ri?t' Grep_Test >> 表示匹配含从rt间有0个或者1 i 的行
  4. [root@allen mnt]# grep -E 'ri{,2}t' Grep_Test >> 表示匹配含从rt间有02 i 的行

在这里插入图片描述

  1. [root@allen mnt]# grep -E 'ri+t' Grep_Test
  2. = grep -E 'ri{1,}t' Grep_Test

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,400人围观)

还没有评论,来说两句吧...

相关阅读