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/