如何在IPython中使用grep?
我安装了PythonXY。请问我该如何在IPython中使用或安装grep
或者类似grep
的功能呢?它提示grep
没有定义。我想在一个文件夹里的文本文件中搜索文本。
3 个回答
0
我知道现在回答有点晚,但我刚完成了一个简单的项目,正好实现了这个功能!
安装
pip install greps
使用方法
%load_ext greps
In [1]: {i:i for i in range(3)}
Out[1]:
{0: 0,
1: 1,
2: 2,
}
In [2]: %greps 1
Out[2]: ' 1: 1,\n'
你可以在这个链接找到更多信息:https://github.com/royreznik/greps
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
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/*')