周顺的技术博客

  • 1. grep基本语法
  • 2. grep案例演示
  • 首页
  • 榜上有名
  • 文章归档
  • 读者排行
  • 豆瓣书影
  • 友情链接
  • DevOps (4)
  • Docker (4)
  • k8s (9)
  • linux (11)
  • Mysql (9)
  • Python (2)
  • Redis (1)
  • Shell (6)
  • 主题 (0)
  • 未分类 (0)

Shell三剑客之grep指令

  • xiaoteng
  • 2024-03-01
  • 0

1. grep基本语法

grep主要作用:过滤来自一个文件或标准输入匹配模式内容(查找、过滤)。

除了 grep 外,还有 egrep。egrep 是 grep 的扩展,相当于 grep -E。

基本语法:grep [OPTION]... PATTERN [FILE]...

记住:都是常见一些选项

支持的正则描述
-E,--extended-regexp模式是扩展正则表达式(ERE) => 字符簇、()、|或
-P,--perl-regexp模式是Perl正则表达式 => \d、\w、\s
-i,--ignore-case忽略大小写
-w,--word-regexp模式匹配整个单词
-v,--invert-match打印不匹配的行(取反)

输出控制描述
-n,--line-number打印行号
-o,--only-matching只打印匹配的内容
-r,--recursive递归目录
-c,--count统计匹配行数

2. grep案例演示

准备数据集

# vim demo.txt
Hello, this is an example file.
It contains some lines of text.
Let's use grep to search for specific patterns.

案例1:在文件中搜索包含单词 "example" 的行

# grep "example" demo.txt

案例2:忽略大小写地搜索匹配模式的行

在文件中搜索不区分大小写的单词 "hello"的行
# grep -i "hello" demo.txt

案例3:反转匹配,只打印不匹配模式的行

在文件中搜索不包含"text"的行
# grep -v "text" demo.txt

案例4:显示匹配行的行号

在文件中搜索包含单词 "example" 的行,并显示行号
# grep -n "example" demo.txt

案例5:统计匹配的行数

# grep -c "example" demo.txt

案例6:仅匹配整个单词

在文件中搜索包含单词 "example" 的行,是整个单词,而不是一个单词的一部分
# grep -w "example" demo.txt

案例7:递归地搜索目录及其子目录下的文件

搜索/root/目录下包含内容"Hello, this is an example file."的所有文件
# grep -r "Hello, this is an example file." /root/
© 2026 周顺的技术博客
Theme by Wing
  • {{ item.name }}
  • {{ item.name }}