Solved Search for a string in a file, print it and the next 5 lines

November 10, 2020 at 01:32:57
Specs: AIX 5.3, 4 CPU / 32 GB RAM
Hello,

I am reading a file on Linux and searching for a string e.g. XXX. I would like to print 'XXX' and also the next 5 files related to the string. I am looking for a python solution.

My methodology has been to loop through the file and print the 'XXX'. I then need to move to the next 5 files and print so I have started a count running.
Can anyone assist so a simplified input file and desired output below:

Input file:
A1323
A2224
A3988
XXX
This line1 relates to XXX
This line2 relates to XXX
This line3 relates to XXX
This line4 relates to XXX
This line5 relates to XXX
C322
D433
E334

Desired output:
XXX
This line1 relates to XXX
This line2 relates to XXX
This line3 relates to XXX
This line4 relates to XXX
This line5 relates to XXX


See More: Search for a string in a file, print it and the next 5 lines


#1
November 10, 2020 at 02:03:14
Your methodology seems correct, so what's the problem?

Reply ↓  Report •

#2
November 10, 2020 at 03:33:12
✔ Best Answer
I got it to run:

outfile = '/home/pydump/input'
flag = 0
count = 0

with open(outfile, 'r') as fh:
for line in fh:
if line.startswith('XXX'):
flag = 1
print(line, end='')
continue

elif flag == 1 :
while count <5:
print(line, end='')
count = count + 1
break


XXX
This line1 relates to XXX
This line2 relates to XXX
This line3 relates to XXX
This line4 relates to XXX
This line5 relates to XXX

Is there a more code efficient way or is this how you would do it? The post has removed my indentations.

message edited by user57


Reply ↓  Report •
Related Solutions


Ask Question