雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

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

2024-07-22 Linux 38

问题描述

在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
更新于:1个月前
赞一波!

文章评论

全部评论