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

2 Comments

  1. A real life simulation that demonstrates how powerful and flexible Python can be with text processing is the Unix command GREP, emulated in Python. It emphasizes such skills as pattern matching, logical reasoning, and writing clean, efficient code that resembles the tools developers of the real world encounter in their everyday activity. It is time consuming and concentration demanding to work through assignments of this nature, particularly when exams are piled on one another in various subjects. It is usually that stress which makes students begin to seek out do my class for me services so that they can handle the loads of work, yet still continue to track their learning.

    ReplyDelete
Previous Post Next Post