I have installed PythonXY. How do I use or install grep
or a grep
like function in IPython? It gives an error that grep
is not defined. I want to search for text in text files in a directory.
Asked
Active
Viewed 5,824 times
5

famousgarkin
- 13,687
- 5
- 58
- 74

user3518093
- 69
- 1
- 3
-
See [using grep in python in SO](https://stackoverflow.com/questions/9018109/using-grep-in-python) – Tengis Apr 10 '14 at 06:36
-
which os you are working on? – venpa Apr 10 '14 at 06:47
-
2Why use grep? Why not use Python's own regex functions? Load the file and search it. – sashoalm Apr 10 '14 at 07:20
-
I am on a windows system – user3518093 Nov 22 '14 at 07:00
2 Answers
3
With just python (>=2.5) code:
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
Then you can use it this way:
grep('text', 'path/to/files/*')

Claudio
- 927
- 7
- 15
2
Assuming you are on a *nix system you can do:
File: file_1.txt
this is line one
this is line two
this is line three
Code:
import os
import subprocess
os.system('grep one file_1.txt')
subprocess.call(['grep', 'one', 'file_1.txt'])
Output in both cases:
this is line one

skamsie
- 2,614
- 5
- 36
- 48