在当前目录中和下方的所有文件中查找特定单词

我想找到所有文件,并打印路径和文件名,用于任何使用文本“Numlock”的文件 – 无论是低级,高级还是混合大小写。

我应该使用什么命令?

下面的脚本以递归方式搜索给定目录中的(文本)文件,以查找给定字符串的出现,无论它是大写还是小写,或者它们的任意组合。

它将为您提供找到的匹配列表,文件路径,文件路径以及文件中字符串的实际出现情况,如下所示:

 /path/to/file1 ['numlock', 'numlocK'] /longer/path/to/file2 ['NuMlOck'] 

等等

为了限制搜索时间,我会在特定目录中查找匹配项,因此不会查找2TB文件;)。

要使用它:

1]复制下面的文本,将其粘贴到空文本文件(gedit)中。 2]编辑headsection中的两行以定义要查找的字符串和要搜索的目录。 3]将其另存为searchfor.py。 4]运行它:打开一个终端,键入python3 + space ,然后将脚本拖到终端python3并按回车键。 找到的匹配列表将显示在terminalwindow中

如果出现错误,脚本会提到它。

 #!/usr/bin/python3 import os #----------------------------------------------------- # give the searched word here in lowercase(!): searchfor = "string_to_look_for" # give the aimed directory here: searchdir = "/path/to/search" #----------------------------------------------------- wordsize = len(searchfor) unreadable = [] print("\nFound matches:") for root, dirs, files in os.walk(searchdir, topdown=True): for name in files: file_subject = root+"/"+name try: with open(file_subject) as check_file: words = check_file.read() words_lower = words.lower() found_matches_list = [i for i in range(len(words_lower)) if words_lower.startswith(searchfor, i)] found_matches = [words[index:index+wordsize] for index in found_matches_list] if len(found_matches) != 0: print(file_subject, found_matches) else: pass except Exception: unreadable.append(file_subject) if len(unreadable) != 0: print("\ncould not read the following files:") for item in unreadable: print("unreadable:", item) 

您可以使用grep -r对文件内容进行递归搜索,例如

 grep -Iri 'numlock' /path/to/search/dir/ 

其中/path/to/search/dir/是您要从中开始搜索的顶级目录 – 您可以使用/但要为它做好准备需要很长时间。

一些变化,取决于您的确切要求:

  • 如果要遵循符号链接,请将-r选项更改为-R
  • 添加-l选项以仅打印找到的文件的名称

I告诉grep忽略二进制文件,而i使搜索不区分大小写。

如果您的grep版本不支持递归搜索,则可以使用find和grep的组合来实现相同的function,例如

 find /path/to/search/dir/ -type f -exec grep --color -HIi 'numlock' {} +