5

我已经安装了 PythonXY。如何在 IPython 中使用或安装grep或类似功能?grep它给出了一个grep未定义的错误。我想在目录中的文本文件中搜索文本。

4

2 回答 2

3

仅使用 python (>=2.5) 代码:

import fileinput
import re
import glob

def grep(PAT, FILES):
    for line in fileinput.input(glob.glob(FILES)):
        if re.search(PAT, line):
            print fileinput.filename(), fileinput.lineno(), line

然后你可以这样使用它:

grep('text', 'path/to/files/*')
于 2015-09-01T13:43:13.353 回答
2

假设您在 *nix 系统上,您可以执行以下操作:

文件:file_1.txt

this is line one
this is line two
this is line three

代码:

import os
import subprocess

os.system('grep one file_1.txt')
subprocess.call(['grep', 'one', 'file_1.txt'])

两种情况下的输出:

this is line one
于 2014-04-10T07:15:09.647 回答