
linux grep 递归
grep
is very useful command to search files and directories. What makes grep
powerful is that it can search file contents. We can search file content according to extension. Recursive behavior makes it more powerful by looking sub directories and files.
grep
是搜索文件和目录的非常有用的命令。 使grep
功能强大的原因是它可以搜索文件内容。 我们可以根据扩展名搜索文件内容。 通过查看子目录和文件,递归行为使其更强大。
Introduction to Linux Grep Command With Examples
递归-r选项(Recursive -r Option)
We will start with a simple example and only specifying recursive option -r
which is shortcut for “recursive”. In this example we will search files those have string import
. We will search /home
directory.
我们将从一个简单的示例开始,仅指定递归选项-r
,这是“递归”的快捷方式。 在此示例中,我们将搜索具有字符串import
文件。 我们将搜索/home
目录。
$ grep -r "import" /home/

指定文件名模式或扩展名(Specify File Name Pattern or Extension)
We can specify file pattern to search recursively. For example if we want to search the Python script or code files content we can use *.py
file pattern to look only those files recursively. In this example we will search for import
term. We will use --include
option.
我们可以指定文件模式以进行递归搜索。 例如,如果我们要搜索Python脚本或代码文件的内容,可以使用*.py
文件模式来递归地仅查看那些文件。 在此示例中,我们将搜索import
项。 我们将使用--include
选项。
$ grep -r --include "*.py" "python3" /home/

排除指定的文件名模式或扩展名(Exclude Specified File Name Pattern or Extension)
We can also specify the file name patterns or extensions we want to exclude. For example if we only want to search python scripts but not pyc
or python cache files we can specify to exclude pyc
. We will use --exclude
option for this.
我们还可以指定我们要排除的文件名模式或扩展名。 例如,如果我们只想搜索python脚本而不是pyc
或python缓存文件,则可以指定排除pyc
。 我们将为此使用--exclude
选项。
$ grep -r --exclude "*.pyc" "python3" /home/
搜索不区分大小写 (Search Case-Insensitive)
By default grep
will search case sensitive. Case sensitive will look exact term. If we want to look incase-sensitive we should provide -i
option. In this example we will search test
case-insensitive which means alternative like TEST
Test
etc. will be looked for.
默认情况下, grep
将搜索区分大小写的内容。 区分大小写将看起来确切的术语。 如果我们希望区分大小写,则应提供-i
选项。 在此示例中,我们将搜索不区分大小写的test
,这意味着将查找诸如TEST
Test
等的替代项。
$ grep -r -i "test" /home/

搜索多个目录(Search Multiple Directories)
In previous examples we have provide only single directory to search. In some cases we may need to search multiple directories those resides in different path. In this example we will search directories /etc
/usr/shareand
/home` in single command by adding them to the end of the command.
在前面的示例中,我们仅提供单个目录进行搜索。 在某些情况下,我们可能需要搜索驻留在不同路径中的多个目录。 在此示例中,我们将在单个命令中搜索目录/etc
/ usr / share and
/ home`,方法是将它们添加到命令末尾。
$ grep -r -i "test" /etc/ /usr/share/ /home/

翻译自: https://www.poftut.com/use-grep-command-recursively-sub-directories-linux/
linux grep 递归