侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

Linux中如何按关键字搜索文本文件

码峰
2022-10-14 / 0 评论 / 0 点赞 / 676 阅读 / 320 字 / 正在检测是否收录...
广告 广告

问题描述

在Linux中,有时候想指定关键字或规则匹配搜索指定目录及其子目录中的所有文本文件,并打印出匹配的文件和对应的行号,使用grep命令可以进行递归搜索。

使用grep命令进行搜索

grep -rnw '/path/to/somewhere/' -e 'pattern'

参数说明:
-r or -R is recursive (表示递归搜索所有子目录)
-n is line number (输出结果是否打印行号)
-w stands for match the whole word. (是否整字匹配)
-l (lower-case L) can be added to just give the file name of matching files.
-e is the pattern used during the search (搜索匹配规则)
使用 --exclude, --include, --exclude-dir 选项可以指定包含或排除文件或目录

如下命令表示只搜索 .c or .h 文件:

grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"

以下命令表示排除.o类型的文件:

grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"

对于目录搜索,可以使用 --exclude-dir 排除多个目录。例如,以下命令会排除 dir1/, dir2/ 整个目录,以及所有匹配*.dst的目录

grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
0
广告 广告

评论区