Title:
[Linux] grep的用法
1- 前言
grep
是一个在 Unix 和 Linux 系统中用于搜索文本的命令行工具。它可以用来在文件中查找符合指定模式的文本,并输出包含该模式的行。以下是 grep
的基本用法和常见选项。
2- 基本用法
grep [选项] 模式 文件
例如,搜索文件 example.txt
中包含 “hello” 的行:
grep "hello" example.txt
3- 常见选项
-i: 忽略大小写
grep -i "hello" example.txt
-v: 反转匹配,显示不包含模式的行
grep -v "hello" example.txt
-r: 递归搜索目录中的所有文件
grep -r "hello" /path/to/directory
-l: 只显示包含匹配模式的文件名
grep -l "hello" *
-n: 显示匹配行的行号
grep -n "hello" example.txt
-c: 只输出匹配的行数
grep -c "hello" example.txt
-w: 匹配整个单词
grep -w "hello" example.txt
-A NUM: 在匹配行后显示指定数量的行
grep -A 3 "hello" example.txt
-B NUM: 在匹配行前显示指定数量的行
grep -B 3 "hello" example.txt
-C NUM: 在匹配行前后各显示指定数量的行
grep -C 3 "hello" example.txt
4- 使用正则表达式
grep
也可以使用正则表达式进行高级搜索。默认情况下,grep
使用基本正则表达式(BRE),使用 -E
选项可以启用扩展正则表达式(ERE)。
基本正则表达式:
grep "hel.lo" example.txt
.
: 匹配任意单个字符(除了换行符)
扩展正则表达式:
grep -E "hel+o" example.txt
l+
: 匹配一个或多个字符 ‘l’。在扩展正则表达式中,+
表示前面的字符可以出现一次或多次
正则表达式(Regular Expression,简称regex或regexp)是一种用来描述或者匹配字符串的模式。它可以用来搜索、编辑或操作文本。
5- 结合其他命令
grep
通常与其他命令一起使用,通过|
进行数据处理。例如,从 ps
命令的输出中查找所有运行的 “ssh” 进程:
ps aux | grep ssh
6- 示例
- 在目录
./rgr_log_dir
下的所有.log
文件中查找 “UVM_ERROR” 并输出到regress_2.log
:
grep 'UVM_ERROR' -R ./rgr_log_dir/*.log > regress_2.log
- 查找包含 “UVM_ERROR” 或 “ui_ns” 的行,并将结果输出到
regress_3.log
:
grep -E 'UVM_ERROR|ui_ns' -R ./rgr_log_dir/*.log > regress_3.log
7- 小结
grep
是一个功能强大的文本搜索工具,可以通过多种选项和正则表达式进行灵活的文本匹配和处理。在使用 grep
时,可以根据具体需求选择合适的选项来完成文本搜索任务。
📨认知有限欢迎指导,本文持续更新中…