Home > Back-end >  How do I get information after a certain sentence in a txt file?
How do I get information after a certain sentence in a txt file?

Time:10-10

I have a text file regarding different information about Ip addresses after a test has been completed. I want to print out this information, how?

The text file is called "IPAddressesTEST.log"

a part of the text follows like this

Connected IPv6's:

(and here is the ipv6 address)

CodePudding user response:

If we assume the "IPAddressesTEST.log" looks like this:

junk 
stuff
Connected IPv6's:
2345:0425:2CA1:0000:0000:0567:5673:23b5
foo
bar
Connected IPv6's:
2392:0411:2CB2:0000:0000:0567:5226:24ba
more stuff
more junk

Then the following will print out the lines immediately following a line containing the string "Connected IPv6's:"

with open('IPAddressesTEST.log', 'r', encoding='utf-8') as f:
    lines = f.readlines()

for counter, line in enumerate(lines):
    if "Connected IPv6's:" in line:
        print(lines[counter  1].strip())

Output:

2345:0425:2CA1:0000:0000:0567:5673:23b5
2392:0411:2CB2:0000:0000:0567:5226:24ba

CodePudding user response:

import re
pattern = "(?<=Connected IPv6's:\n)\S*"
text = "Connected IPv6's:\n2345:0425:2CA1:0000:0000:0567:5673:23b5"
re.findall(pattern,text)

output:

['2345:0425:2CA1:0000:0000:0567:5673:23b5']

  • Related