I have been writing a program that searches a file in 3 different ways. But firstly, to choose which search program to use is differentiated in the command line.
For example in the command line I type:
Program 1 search: python file.py 'search_term' 'file-to-be-searched'
program 2 search: python file.py -z 'number' 'search_term' 'file-to-be-searched'
program 3 search: python file.py -x 'search_term' 'file-to-be-searched'
All 3 search scripts are in the file.py.
The coding I have so far is:
import re
import sys
#program 1
search_term = sys.argv[1]
f = sys.argv[2]
for line in open(f, 'r'):
if re.search(search_term, line):
print line,
# Program 2
flag = sys.argv[1]
num = sys.argv[2]
search_term = sys.argv[3]
f = sys.argv[4]
#program 3
flag = sys.argv[1]
search_term = sys.argv[2]
f = sys.argv[3]
for line in open(f, 'r'):
if re.match(search_term, line):
print line,
Program 1 works fine thats no problem. Program 2, finds the search-term in the file and prints out a number of lines before and after it defined by the 'number' parameter, but i have no idea about how to do this. Program 3 finds the exact match from the search-term and prints out all the lines after the search_term. re.match is inadequate because it only searches from the beginning of a string it does not consider the rest.
My final problem how would I differentiate between the three programs? using the flags or no flag from the command line?
Any help would be appreciated.
Thanks