finding string in file

All

Script to find string in file

To run in a directory:

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

import sys

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

def find_line(file, string_search):
print(“XXXX”)
import re
errors = []
linenum = 0
pattern = re.compile(r””+string_search)
with open (file, ‘rt’) as myfile:
for line in myfile:
linenum += 1
if pattern.search(line) != 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

#Main:
is_there = find(file_name, string_name)
print(is_there)
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:

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s