0

I have a python script that I'm using to parse a log file and print out matching errors, etc. What I'd like to do is also print the line number that the matching entry was found on.

I've seen a few similar posts such as; Search File And Find Exact Match And Print Line? But I haven't been able to apply the examples successfully.

My code is:

from sys import argv

script, filename = argv

with open(filename) as f:
        data = f.read().splitlines()
        # Process counts and matches of events:
        assertmatch = [s for s in data if "Assertion" in s]
        assertcount = len(assertmatch)

if assertcount > 0:
    print " "
    print "ASSERTIONS:"
    print '\n'.join([str(myelement) for myelement in assertmatch])
Community
  • 1
  • 1
FunnyChef
  • 1,880
  • 3
  • 18
  • 30

3 Answers3

0

You can read each line into a dictionary with the key being the line number then run your matching algorithm on each dictionary item. If it matches, print the key.

content = {}

with open(filename) as f:
    lineNum = 0
    for line in f:
        content[lineNum] = line
        lineNum = lineNum + 1

# Do search for each in content, if match, print line key.
Shawn
  • 667
  • 8
  • 19
0
print [(i,line) for i,line in enumerate(open(filename),1) if "Assertion" in line]
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

I can build your assertmatch using enumerate. The code would be something like the following:

assertmatch = []
for i, s in enumerate(data, 1):
    if "Assertion" in s:
        assertmatch.append('Line %05d: %s' % (i, s,))

There is no need to change the remaining code.

Fabio Menegazzo
  • 1,191
  • 8
  • 9