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

查看:17
本文介绍了如何在 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 为行号,
  • -w 代表全词匹配.
  • -l(小写L)可以添加,只给出匹配文件的文件名.
  • -e 是搜索时使用的模式
    • -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.
    • -e is the pattern used during the search
    • 除了这些,--exclude--include--exclude-dir 标志可用于高效搜索:

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

      • 这只会搜索那些扩展名为 .c 或 .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/的目录:
          • For directories it's possible to exclude one or more directories using the --exclude-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.

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

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