Adam104 Adam104 - 4 months ago 8
Linux Question

Find if a specific string exists after a specific string on the following line

I'm creating a script in which i'm looking for a specific string in a file, then print the next 5 following lines, However, the initial string could be found in other areas of the file and are unnecessary, So i'm trying to add an additional check to see if the next line contains a specific string then print the content if not, don't print it:

f = open(i, 'r')
msg = 'somestring'
for line in f:
if msg in line: # I would like to add a check if a specific (**somestring following
# the msg on the next line**) exists on the next line, string here
for string in range(5):
print line + ''.join(islice(f, 5))

Answer

First attempt:

from itertools import islice

first_string = 'Description = "'
second_string = 'ErrorCode'

with open('test.txt') as f:
    for line in f:
        if first_string in line:
            next_line = next(f)
            if second_string in next_line:
                print(next_line + ''.join(islice(f, 4)))

test.txt:

Description = "Something"
FalseAlarm = true

Description = "Something"
ErrorCode 0
EstimatedInstallTime = 30
EvaluationState = 1
Something = Else
More = Here

Output:

ErrorCode 0
EstimatedInstallTime = 30
EvaluationState = 1
Something = Else
More = Here