finding string in file


Script to find string in file

To run in a directory:

fdemeloj@fdemeloj directory]$ for f in *; do python  $f; done

import sys

def find(file, string_search):
with open(file) as myfile:
if string_search in
return True
return False

def find_line(file, string_search):
import re
errors = []
linenum = 0
pattern = re.compile(r””+string_search)
with open (file, ‘rt’) as myfile:
for line in myfile:
linenum += 1
if != None: # If pattern search finds a match,
errors.append((linenum, line.rstrip(‘\n’)))
for err in errors:
print(“Line “, str(err[0]), “: ” + err[1])

file_name = sys.argv[1]
string_name = “string”

print “This is the name of the script: “, sys.argv[0]
print “This is the file: “, sys.argv[1]
if len(sys.argv) > 2:
print “This is the string to find: “, sys.argv[2]
string_name = str(sys.argv[2])
print “This is the name of the string: “, string_name

is_there = find(file_name, string_name)
if is_there is True:
find_line(file_name, string_name)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s