Simulate Unix GREP command in Python

Grep command :- Grep searches the named input FILE's (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN.
By default, grep prints the matching lines.takes 2 parameters "source" and "pattern" that need to be searched.

Sample program simulating grep command:-  

Create a file(fgrepwc.py) with following sample code. Here three command line argument is passed "" i.e : python fgrepwc.py "world" input.txt.

import sys
import string

def findpatterninfile(pattern, filename):
    count = 0
    try:
        filehandle = open(filename,'r')
    except:
        print filename, ":", sys.exec_info()[1]
    allLines = filehandle.readlines()
    filehandle.close()

    for line in allLines :
        if string.find(line,pattern) > -1:
            count = count+1
            sys.stdout.write(line)
    print "\nTotal pattern match count is : " + str(count)
        
def errorreport():
    print "Invalid input/usage"
    sys.exit(1)
    
def validateArgs():
    #agrc = len(sys.argv)
    if len(sys.argv) != 3:
        errorreport()
    else:
        findpatterninfile(sys.argv[1],sys.argv[2])
#Executed directly as application
if __name__ == '__main__':
    validateArgs()

Content of input.txt:- 

Hello world
Read first line.
Python world
world is game

Sample output:- Create input.txt with above lines and execute following command -

> python fgrepwc.py "world" input.txt
Hello world
Python world
world is game
Total line count is : 3

1 Comments

Previous Post Next Post