How do I print a certain sentence from a file?

I’m trying to print a certain sentence from an external file in python. The file is a .log file.

This is how the file written:

[Mon Dec 05 14:01:48 2005] [notice] workerEnv.init() ok /etc/httpd/conf/workers2.properties
[Mon Dec 05 14:01:48 2005] [error] mod_jk child workerEnv in error state 7

I want to print everything in the first [ ] and everything after [notice] or [error].
I think I need to use the split command but I don’t know how.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Something like this should work:

import re

with open('logfile.log') as logfile:
    for line in map(str.strip, logfile):
        m = re.findall('[.*?]', line)
        if len(m) > 1 and m[1] in ('[notice]', '[error]'):
            offset = line.find(m[1]) + len(m[1]) + 1
            print(m[0], line[offset:])

Note:

There are no validity checks here. If a line in the log file doesn’t exactly match the format shown in the question, this could fail

Method 2

You can do it like this, but probably it won’t be the fastest way…

text = ['[Mon Dec 05 14:01:48 2005] [notice] workerEnv.init() ok /etc/httpd/conf/workers2.properties',
        '[Mon Dec 05 14:01:48 2005] [error] mod_jk child workerEnv in error state 7']

for line in text:
    kw = '[notice]' if line.find('[notice]') >= 0 else '[error]' if line.find('[error]') >= 0 else None
    # Filter out every line which does not contain '[notice]' or '[error]'
    if kw:
        tmp = line.split(kw)
        # [1:-2] is needed to get rid of the '[' and ']'
        print(tmp[0][1:-2], tmp[1])


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x