5

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.

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
user3518093
  • 69
  • 1
  • 3

2 Answers2

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