如何查找Linux上包含特定文本的所有文件?

[英]How do I find all files containing specific text on Linux?


I'm trying to find a way to scan my entire Linux system for all files containing a specific string of text. Just to clarify, I'm looking for text within the file, not in the file name.

我正在寻找一种方法来扫描整个Linux系统中包含特定文本字符串的所有文件。澄清一下,我在文件中查找文本,而不是文件名。

When I was looking up how to do this, I came across this solution twice:

当我在寻找如何做到这一点时,我两次遇到了这个解决方案:

find / -type f -exec grep -H 'text-to-find-here' {} \;

However, it doesn't work. It seems to display every single file in the system.

然而,它不工作。它似乎显示了系统中的每个文件。

Is this close to the proper way to do it? If not, how should I? This ability to find text strings in files would be extraordinarily useful for some programming projects I'm doing.

这接近正确的方法吗?如果没有,我该怎么做?这种在文件中查找文本字符串的能力对于我正在做的一些编程项目非常有用。

41 个解决方案

#1


6438  

Do the following:

执行以下操作:

grep -rnw '/path/to/somewhere/' -e 'pattern'
  • -r or -R is recursive,
  • -r或-r是递归的,
  • -n is line number, and
  • n是行号,和
  • -w stands for match the whole word.
  • -w代表匹配整个单词。
  • -l (lower-case L) can be added to just give the file name of matching files.
  • -l(小写的L)可以添加为匹配文件的文件名。

Along with these, --exclude, --include, --exclude-dir flags could be used for efficient searching:

除了这些之外,排除,包括,排除-dir标记可以用于高效搜索:

  • This will only search through those files which have .c or .h extensions:

    这将只搜索那些有.c或.h扩展名的文件:

    grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
    
  • This will exclude searching all the files ending with .o extension:

    这将排除搜索所有以.o扩展名结尾的文件:

    grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
    
  • For directories it's possible to exclude a particular directory(ies) through --exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:

    对于目录,可以通过排除dir参数排除特定目录。例如,这将排除dirs dir1/、dir2/以及所有匹配*.dst/:

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

This works very well for me, to achieve almost the same purpose like yours.

这对我来说很有效,可以达到和你一样的目的。

For more options check man grep.

对于更多的选项,检查man grep。

#2


1046  

You can use grep -ilR:

您可以使用grep -ilR:

grep -Ril "text-to-find-here" /
  • i stands for ignore case (optional in your case).
  • 我代表忽略情况(在你的情况下是可选的)。
  • R stands for recursive.
  • R代表递归。
  • l stands for "show the file name, not the result itself".
  • l代表“显示文件名,而不是结果本身”。
  • / stands for starting at the root of your machine.
  • /代表从机器的根开始。

#3


225  

You can use ack. It is like grep for source code. You can scan your entire file system with it.

您可以使用ack。它就像源代码的grep。您可以用它扫描整个文件系统。

Just do:

只做:

ack 'text-to-find-here'

In your root directory.

在你的根目录。

You can also use regular expressions, specify the filetype, etc.

您还可以使用正则表达式、指定文件类型等。


UPDATE

更新

I just discovered The Silver Searcher, which is like ack but 3-5x faster than it and even ignores patterns from a .gitignore file.

我刚刚发现了Silver Searcher,它的速度比ack快3-5倍,甚至忽略了.gitignore文件中的模式。

#4


118  

You can use:

您可以使用:

grep -r "string to be searched"  /path/to/dir

The r stands for recursive and so will search in the path specified and also its sub-directories. This will tell you the file name as well as print out the line in the file where the string appears.

r表示递归,因此将在指定的路径和子目录中搜索。这将告诉您文件名,并打印出字符串出现的文件中的行。

Or a command similar to the one you are trying (example: ) for searching in all javascript files (*.js):

或类似于您正在尝试的命令(示例:),用于在所有javascript文件中搜索(*.js):

find . -name '*.js' -exec grep -i 'string to search for' {} \; -print

This will print the lines in the files where the text appears, but it does not print the file name.

这将在显示文本的文件中打印行,但不会打印文件名。

In addition to this command, we can write this too: grep -rn "String to search" /path/to/directory/or/file -r: recursive search n: line number will be shown for matches

除了这个命令,我们还可以编写以下命令:grep -rn“要搜索的字符串”/path/to/directory/或/file -r:递归搜索n:将显示匹配的行号

#5


79  

You can use this:

您可以使用:

grep -inr "Text" folder/to/be/searched/

#6


44  

If your grep doesn't support recursive search, you can combine find with xargs:

如果您的grep不支持递归搜索,可以将find与xargs结合:

find / -type f | xargs grep 'text-to-find-here'

I find this easier to remember than the format for find -exec.

我发现这比find -exec的格式更容易记住。

This will output the filename and the content of the matched line, e.g.

这将输出文件名和匹配行的内容,例如。

/home/rob/file:text-to-find-here

Optional flags you may want to add to grep:

您可能想要添加到grep的可选标志:

  • -i - case insensitive search
  • -大小写不敏感搜索
  • -l - only output the filename where the match was found
  • -只输出匹配的文件名。
  • -h - only output the line which matched (not the filename)
  • -h -只输出匹配的行(不是文件名)

#7


44  

List of file names containing a given text

First of all, I believe you have used -H instead of -l. Also you can try adding the text inside quotes followed by {} \.

首先,我相信你用的是-H而不是-l。还可以尝试在引号后面加上{}\。

find / -type f -exec grep -l "text-to-find-here" {} \; 

Example

Let's say you are searching for files containing specific text "Apache License" inside your directory. It will display results somewhat similar to below (output will be different based on your directory content).

假设您正在搜索目录中包含特定文本“Apache License”的文件。它将显示与下面类似的结果(输出将根据目录内容不同)。

bash-4.1$ find . -type f -exec grep -l "Apache License" {} \; 
./net/java/jvnet-parent/5/jvnet-parent-5.pom
./commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.pom
./io/swagger/swagger-project/1.5.10/swagger-project-1.5.10.pom
./io/netty/netty-transport/4.1.7.Final/netty-transport-4.1.7.Final.pom
./commons-codec/commons-codec/1.9/commons-codec-1.9.pom
./commons-io/commons-io/2.4/commons-io-2.4.pom
bash-4.1$ 

Remove case sensitiveness

Even if you are not use about the case like "text" vs "TEXT", you can use the -i switch to ignore case. You can read further details here.

即使您不使用“text”和“text”这样的大小写,您也可以使用-i开关来忽略大小写。你可以在这里阅读更多的细节。

Hope this helps you.

希望这能帮助你。

#8


33  

grep -insr "pattern" *
  • i: Ignore case distinctions in both the PATTERN and the input files.
  • i:忽略模式和输入文件中的区分情况。
  • n: Prefix each line of output with the 1-based line number within its input file.
  • n:在每个输出行前面加上输入文件中基于1的行号。
  • s: Suppress error messages about nonexistent or unreadable files.
  • s:抑制不存在或不可读文件的错误消息。
  • r: Read all files under each directory, recursively.
  • 递归地读取每个目录下的所有文件。

#9


27  

grep (GNU or BSD)

You can use grep tool to search recursively the current folder, like:

您可以使用grep工具递归地搜索当前文件夹,例如:

grep -r "class foo" .

Note: -r - Recursively search subdirectories.

注意:-r -递归搜索子目录。

You can also use globbing syntax to search within specific files such as:

您还可以使用globbing语法搜索特定文件,例如:

grep "class foo" **/*.c

Note: By using globbing option (**), it scans all the files recursively with specific extension or pattern. To enable this syntax, run: shopt -s globstar. You may also use **/*.* for all files (excluding hidden and without extension) or any other pattern.

注意:通过使用globbing选项(**),它以特定的扩展名或模式递归地扫描所有文件。要启用此语法,运行:shopt -s globstar。您也可以使用**/*。*适用于所有文件(不包括隐藏和无扩展)或任何其他模式。

If you've the error that your argument is too long, consider narrowing down your search, or use find syntax instead such as:

如果你发现你的论点太长了,考虑缩小搜索范围,或者使用查找语法,比如:

find . -name "*.php" -execdir grep -nH --color=auto foo {} ';'

Alternatively use ripgrep.

或者使用ripgrep。

ripgrep

If you're working on larger projects or big files, you should use ripgrep instead, like:

如果您正在处理较大的项目或大文件,您应该使用ripgrep,比如:

rg "class foo" .

Checkout the docs, installation steps or source code on the GitHub project page.

在GitHub项目页面上签出文档、安装步骤或源代码。

It's much quicker than any other tool like GNU/BSD grep, ucg, ag, sift, ack, pt or similar, since it is built on top of Rust's regex engine which uses finite automata, SIMD and aggressive literal optimizations to make searching very fast.

它比任何其他工具(如GNU/BSD grep、ucg、ag、sift、ack、pt或类似工具)都要快得多,因为它构建在Rust的regex引擎之上,该引擎使用有限自动机、SIMD和积极的文字优化使搜索非常快速。

It supports ignore patterns specified in .gitignore files, so a single file path can be matched against multiple glob patterns simultaneously.

它支持在.gitignore文件中指定的忽略模式,因此可以同时对多个glob模式匹配单个文件路径。


You can use the common parameters such as:

您可以使用以下常用参数:

  • -i - Insensitive searching.
  • 我——不敏感搜索。
  • -I - Ignore the binary files.
  • -忽略二进制文件。
  • -w - Search for the whole words (in opposite of partial word matching).
  • -w -搜索整个单词(与部分单词匹配相反)。
  • -n - Show the line of your match.
  • -n -显示你的匹配线。
  • -C/--context (e.g. -C5) - Increases context, so you see the surrounding code .
  • -c /- context(例如- c5) -增加context,这样你就能看到周围的代码。
  • --color=auto - Mark up the matching text.
  • -color=自动标记匹配的文本。
  • -H - Displays filename where the text is found.
  • - h -显示找到文本的文件名。
  • -c - Displays count of matching lines. Can be combined with -H.
  • -c -显示匹配行数。可以和-H结合。

#10


24  

Try:

试一试:

find . -name "*.txt" | xargs grep -i "text_pattern"

#11


21  

Use pwd to search from any directory you are in, recursing downward

使用pwd搜索你所在的任何目录,递归向下。

grep -rnw `pwd` -e "pattern"

Update Depending on the version of grep you are using, you can omit pwd. On newer versions . seems to be the default case for grep if no directory is given thus:

根据您正在使用的grep版本进行更新,您可以省略pwd。在新版本上。如果没有给定目录,那么grep似乎是默认情况:

grep -rnw -e "pattern"

grep -rnw - e“模式”

or

grep -rnw "pattern"

grep -rnw“模式”

will do the same thing as above!

将做同样的事情,如上!

#12


21  

There's a new utility called The Silversearcher

有一个新的实用程序叫做银搜索器

sudo apt install silversearcher-ag

It works closely with Git and other VCS. So you won't get anything in a .git or another directory.

它与Git和其他VCS密切合作。所以你不会在。git或其他目录中得到任何东西。

You can simply use

你可以简单地使用

ag -ia "Search query"

And it will do the task for you!

它会帮你完成任务的!

#13


14  

grep can be used even if we're not looking for a string.

即使我们不是在寻找字符串,也可以使用grep。

Simply running,

简单地运行,

grep -RIl "" .

will print out the path to all text files, i.e. those containing only printable characters.

将输出到所有文本文件的路径,即只包含可打印字符的文件。

#14


13  

Here are the several list of commands that can be used to search file.

下面是可以用于搜索文件的命令列表。

grep "text string to search” directory-path

grep [option] "text string to search” directory-path

grep -r "text string to search” directory-path

grep -r -H "text string to search” directory-path

egrep -R "word-1|word-2” directory-path

egrep -w -R "word-1|word-2” directory-path

#15


12  

I wrote a Python script which does something similar. This is how one should use this script.

我编写了一个类似的Python脚本。这就是应该如何使用这个脚本。

./sniff.py path pattern_to_search [file_pattern]

The first argument, path, is the directory in which we will search recursively. The second argument, pattern_to_search, is a regular expression which we want to search in a file. We use the regular expression format defined in the Python re library. In this script, the . also matches newline.

第一个参数path是我们将递归搜索的目录。第二个参数pattern_to_search是我们想在文件中搜索的正则表达式。我们使用Python re库中定义的正则表达式格式。在这个脚本中。也匹配换行符。

The third argument, file_pattern, is optional. This is another regular expression which works on a filename. Only those files which matches this regular expression will be considered.

第三个参数file_pattern是可选的。这是另一个在文件名上工作的正则表达式。只考虑与此正则表达式匹配的文件。

For example, if I want to search Python files with the extension py containing Pool( followed by word Adaptor, I do the following,

例如,如果我想用包含池的扩展名py搜索Python文件(后面跟着word Adaptor),我将执行以下操作,

./sniff.py . "Pool(.*?Adaptor"  .*py
./Demos/snippets/cubeMeshSigNeur.py:146 
./Demos/snippets/testSigNeur.py:259 
./python/moose/multiscale/core/mumbl.py:206 
./Demos/snippets/multiComptSigNeur.py:268 

And voila, it generates the path of matched files and line number at which the match was found. If more than one match was found, then each line number will be appended to the filename.

然后,它生成匹配文件的路径和找到匹配的行号。如果找到了多个匹配项,则将把每个行号附加到文件名。

#16


12  

find /path -type f -exec grep -l "string" {} \;

Explanation from comments

解释与评论

find is a command that lets you find files and other objects like directories and links in subdirectories of a given path. If you don't specify a mask that filesnames should meet, it enumerates all directory objects.

find是一个命令,允许您在给定路径的子目录中查找文件和其他对象,如目录和链接。如果不指定文件名称应该满足的掩码,则枚举所有目录对象。

-type f specifies that it should proceed only files, not directories etc.
-exec grep specifies that for every found file, it should run grep command, passing its filename as an argument to it, by replacing {} with the filename

#17


12  

Try:

试一试:

find / -type f -exec grep -H 'text-to-find-here' {} \;

which will search all file systems, because / is the root folder.

它将搜索所有文件系统,因为/是根文件夹。

For home folder use:

主文件夹的使用:

find ~/ -type f -exec grep -H 'text-to-find-here' {} \;

For current folder use:

当前文件夹的使用:

find ./ -type f -exec grep -H 'text-to-find-here' {} \;

#18


11  

A Simple find can work handy. alias it in your ~/.bashrc file:

一个简单的发现就可以派上用场。在您的~/中别名。bashrc文件:(

alias ffind find / -type f | xargs grep

Start a new terminal and issue:

开始一个新的终端和问题:

ffind 'text-to-find-here'

#19


10  

Hope this is of assistance...

希望这对您有所帮助……

Expanding the grep a bit to give more information in the output, for example, to get the line number in the file where the text is can be done as follows:

稍微扩展grep以在输出中提供更多信息,例如,获取文本所在文件中的行号,可以如下所示:

find . -type f -name "*.*" -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searthtext"

And if you have an idea what the file type is you can narrow your search down by specifying file type extensions to search for, in this case .pas OR .dfm files:

如果你知道什么是文件类型,你可以通过指定文件类型扩展名来缩小搜索范围,在这种情况下。pa或。dfm文件:

find . -type f \( -name "*.pas" -o -name "*.dfm" \) -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searchtext"

Short explanation of the options:

选择的简短说明:

  1. . in the find specifies from the current directory.
  2. 。在查找中从当前目录中指定。
  3. -name "*.*" : for all files ( -name "*.pas" -o -name "*.dfm" ) : Only the *.pas OR *.dfm files, OR specified with -o
  4. - name”*。*“为所有文件(-name”*)。不是“- o - name”*。只有*。不是或*。dfm文件,或用-o指定
  5. -type f specifies that you are looking for files
  6. 类型f指定您正在查找文件
  7. -print0 and --null on the other side of the | (pipe) are the crucial ones, passing the filename from the find to the grep embedded in the xargs, allowing for the passing of filenames WITH spaces in the filenames, allowing grep to treat the path and filename as one string, and not break it up on each space.
  8. -print0另一边,空的|(管)是至关重要的,通过文件名从发现到grep嵌入式xargs,允许文件名传递文件名的空间,允许grep治疗路径和文件名作为一个字符串,而不是在每个空间分解。

#20


10  

How do I find all files containing specific text on Linux? (...)

如何查找Linux上包含特定文本的所有文件?(…)

I came across this solution twice:

我遇到过两次这样的解决方案:

find / -type f -exec grep -H 'text-to-find-here' {} \;

find / -type f -exec grep -H 'text-to-find-here' {}


If using find like in your example, better add -s (--no-messages) to grep, and 2>/dev/null at the end of the command to avoid lots of Permission denied messages issued by grep and find:

如果在示例中使用find,最好向grep添加-s (- no-message),并在命令末尾添加2>/dev/null,以避免grep发出的大量被拒绝的权限消息,并查找:

find / -type f -exec grep -sH 'text-to-find-here' {} \; 2>/dev/null

find is the standard tool for searching files - combined with grep when looking for specific text - on Unix-like platforms. The find command is often combined with xargs, by the way.

find是在类unix平台上搜索文件的标准工具——在查找特定文本时与grep结合使用。顺便说一下,find命令通常与xargs结合在一起。

Faster and easier tools exist for the same purpose - see below. Better try them, provided they're available on your platform, of course:

为了同样的目的,更快更简单的工具也存在——请参见下面。如果他们在你的平台上,你最好尝试一下:

Faster and easier alternatives

RipGrep - fastest search tool around:

快捷搜索工具:

rg 'text-to-find-here' / -l

The Silver Searcher:

银搜索器:

ag 'text-to-find-here' / -l

ack:

应答:

ack 'text-to-find-here' / -l

Note: You can add 2>/dev/null to these commands as well, to hide many error messages.

注意:您还可以向这些命令添加2>/dev/null,以隐藏许多错误消息。


Warning: unless you really can't avoid it, don't search from '/' (the root directory) to avoid a long and inefficient search! So in the examples above, you'd better replace '/' by a sub-directory name, e.g. "/home" depending where you actually want to search...

警告:除非您确实无法避免,否则不要从'/'(根目录)中搜索,以避免长时间低效的搜索!所以在上面的例子中,你最好用子目录名代替'/',例如。“/home”取决于你想要搜索的地方……

#21


9  

To search for the string and output just that line with the search string:

搜索字符串并输出与搜索字符串相匹配的字符串:

for i in $(find /path/of/target/directory -type f); do grep -i "the string to look for" "$i"; done

e.g.:

例如:

for i in $(find /usr/share/applications -type f); \
do grep -i "web browser" "$i"; done

To display filename containing the search string:

显示包含搜索字符串的文件名:

for i in $(find /path/of/target/directory -type f); do if grep -i "the string to look for" "$i" > /dev/null; then echo "$i"; fi; done;

e.g.:

例如:

for i in $(find /usr/share/applications -type f); \
do if grep -i "web browser" "$i" > /dev/null; then echo "$i"; \
fi; done;

#22


9  

Silver Searcher is a terrific tool, but ripgrep may be even better.

银搜索器是一个很棒的工具,但是绿波可能更好。

It works on Linux, Mac and Windows, and was written up on Hacker News a couple of months ago (this has a link to Andrew Gallant's Blog which has a GitHub link):

它可以在Linux、Mac和Windows上运行,几个月前被写在Hacker News上(这是Andrew Gallant的博客链接,有GitHub链接):

Ripgrep – A new command line search tool

一个新的命令行搜索工具

#23


9  

Use:

使用:

grep -c Your_Pattern *

This will report how many copies of your pattern are there in each of the files in the current directory.

这将报告您的模式在当前目录中的每个文件中有多少个副本。

#24


8  

The below command will work fine for this approach:

下面的命令将适用于这种方法:

find ./ -name "file_pattern_name"  -exec grep -r "pattern" {} \;

#25


7  

grep is your good friend to achieve this.

grep是实现这一目标的好朋友。

grep -r <text_fo_find> <directory>

if you don't care about the case of the text to find then use

如果您不关心要查找的文本的情况,那么请使用

grep -ir <text_to_find> <directory>

#26


6  

If you have a set of files that you will always be checking you can alias their paths, for example:

如果你有一组文件,你将一直检查你可以别名他们的路径,例如:

alias fd='find . -type f -regex ".*\.\(inc\|info\|module\|php\|test\|install\|uninstall\)"'

Then you can simply filter the list like this:

然后你可以像这样简单地过滤列表:

grep -U -l $'\015' $(fd)

Which filters out the list fd to files that contain the CR pattern.

将列表fd过滤到包含CR模式的文件。

I find that aliasing the files that I am interested in helps me create easier scripts then always trying to remember how to get all those files. The recursive stuff works as well but sooner or later you are going to have to contend with weeding out specific file types. Which is is why I just find all the file types I'm interested in to begin with.

我发现让我感兴趣的文件混叠,帮助我创建更容易的脚本,然后总是试图记住如何获取所有这些文件。递归的东西也可以工作,但是迟早您将不得不处理清除特定文件类型的问题。这就是为什么我只找到我感兴趣的所有文件类型。

#27


6  

Avoid the hassle and install ack-grep. It eliminates a lot of permission and quotation issues.

避免麻烦,安装ack-grep。它消除了大量的许可和报价问题。

apt-get install ack-grep

Then go to the directory you want to search and run the command below

然后转到要搜索的目录并运行下面的命令

cd /
ack-grep "find my keyword"

#28


6  

There is an ack tool that would do exactly what you are looking for.

有一个ack工具可以完成您所需要的工作。

http://linux.die.net/man/1/ack

http://linux.die.net/man/1/ack

ack -i search_string folder_path/*

You may ignore -i for case sensitive search

你可以忽略-我是用例敏感搜索。

#29


6  

I am fascinated by how simple grep makes it with 'rl'

我着迷于grep是如何用“rl”做成的

grep -rl 'pattern_to_find' /path/where/to/find

-r to find recursively file / directory inside directories..
-l to list files matching the 'pattern'

Use '-r' without 'l' to see the file names followed by text in which the pattern is found!

使用'-r'而不使用'l'来查看文件名,后面跟着找到模式的文本!

grep -r 'pattern_to_find' /path/where/to/find

Works just perfect..

工作只是完美. .

Hope it helps!

希望它可以帮助!

#30


5  

Try this

试试这个

find . -type f -name some_file_name.xml -exec grep -H PUT_YOUR_STRING_HERE {} \;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/06/06/2c11678f911fa17161819318a8bb17bd.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com