如何在Linux上找到包含特定文本的所有文件? [英] How do I find all files containing specific text on Linux?

查看:170
本文介绍了如何在Linux上找到包含特定文本的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种扫描整个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.

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

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.

推荐答案

执行以下操作:

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




  • -r -R 是递归的,

  • -n 是行号, / li>
  • -w 代表整个字。

  • -l <​​/ code>(小写L)可以添加只是给出匹配文件的文件名。

    • -r or -R is recursive,
    • -n is line number, and
    • -w stands for match the whole word.
    • -l (lower-case L) can be added to just give the file name of matching files.
    • 除了这些, - 排除 - include - exclude-dir - include-dir 标志可用于高效搜索:

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


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

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

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


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

    • This will exclude searching all the files ending with .o extension:

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




      • 就像排除文件一样可能通过 - exclude-dir - include-dir 参数排除/包含目录。例如,这将排除dir dir1 /,dir2 /和它们都匹配* .dst /:

        • Just like exclude files, it's possible to exclude/include directories through --exclude-dir and --include-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.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.

          有关更多选项,请查看 man grep

          For more options check man grep.

          这篇关于如何在Linux上找到包含特定文本的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆