beeloo
beeloo

Reputation: 11

Find a match in line of file, then move on to next file

I'm new in python and I'm try to write a script to loop through all the .txt files in my /home directory and iterate lines in each .txt file and see if I can find a match, if it does, it should move on to next file. If it doesn't find the match in entire file, then report it.

Code that I have:

strname = "ntpq -p"

for file in glob.glob("/home/xxx/*.txt"):
    with open(file, 'rb') as f:
        iFoundTheLine = 0
        for line in f:
            line = line.rstrip()
            id = line.split(b"|")[0]

            if strname in line:
                iFoundTheLine = 1
                print ("%s is ok" % id)
                break

        if iFoundTheLine == 0:
            print ("Problem with NTP%s" % id)

The result that I got:

srv29393 is ok

Problem with NTP

srv29494 is ok

Problem with NTP

srv29399 is ok

srv29493 is ok

The expect result I'm looking for:

srv29393 is ok

Problem with NTP srv1234

srv29494 is ok

Problem with NTP srv2345

srv29399 is ok

srv29493 is ok

sample lines:

srv29393|06/23/18|05:32:02|ps -eo user,pid,ppid,start,etimes,cmd | egrep -v [\w<|>nobody 22972 21597 03:06:12 8767 (dnsserver)

srv29393|06/23/18|05:32:02|1529746322|ps -eo user,pid,ppid,start,etimes,cmd | egrep -v [\w<|>nobody 22973 21597 03:06:12 8767 (dnsserver)

srv29393|06/23/18|05:32:02|ps -eo user,pid,ppid,start,etimes,cmd | egrep -v [\w<|>nobody 22974 21597 03:06:12 8767 (dnsserver)

srv29393|06/23/18|05:32:02|1529746322|/usr/sbin/ntpq -p<|>*1.1.1.11 11.11.11.11 3 u 1055 1024 377 719.042 -0.625 0.016

srv29393|06/23/18|05:32:02|1529746322|/usr/sbin/ntpq -p<|>+2.2.2.11 12.12.12.11 3 u 1049 1024 377 824.784 0.707 0.121

It is missed the "id" for those having issue for the NTP. Could someone please help/advise?

Upvotes: 1

Views: 94

Answers (1)

Melvin Abraham
Melvin Abraham

Reputation: 3036

You have a minor issue. You are trying to print id outside the for loop where the id is not accessible. So, it should be placed inside the loop.

Also, due to this reason, there is no reason that you should have iFoundTheLine variable as it is unnecessary.

EDIT: for line in f should be for line in f.readlines()

With some refactoring of your code:

import glob
strname = "ntpq -p"

for File in glob.glob("/home/xxx/*.txt"):
    with open(File, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            line = line.rstrip()
            id = line.split("<|>")[0]

            if strname in line:
                print ("%s is ok" % id)
                break

            else:
                # Since, `id` is accessible inside the loop 
                print ("Problem with NTP%s" % id)

Since the text file contains special characters, I recommend using UTF-8 encoding with the file rather than accessing it in binary, as it makes the file interaction easier.

Upvotes: 1

Related Questions