1

如何递归搜索包含正则表达式模式的目录下的所有文件?模式是 UTF-8 字符串。

任何使用 Python、Perl 或 bash 的解决方案都是合适的。

4

2 回答 2

4
grep -lr "pattern" /mydirectory/*

它将列出找到模式的 mydirectory 的所有文件。

于 2013-10-26T07:18:15.900 回答
2

使用的 Python 解决方案os.walk

import os
import re

target_dir = '.'
pattern = re.compile(r'blah')

for parent, dirnames, filenames in os.walk(target_dir):
    for fn in filenames:
        filepath = os.path.join(parent, fn)
        try:
            with open(filepath) as f:
                if any(pattern.search(line) for line in f):
                    print(filepath)
        except IOError:
            pass
于 2013-10-26T07:19:03.037 回答