Kumar
Kumar

Reputation: 717

How to grep some string(IP:port) from text file and print in screen using Python?

test.txt:

this is the http ip : 1.1.1.1:678 blah blah.com2
this is the https ip : 1.1.1.2:654 blah blah.com2
this is the http ip : 1.1.1.4:456 blah blah.com2
the sever this is the http ip : 1.1.1.4:456 blah blah.com2

From the above text file, I want to grep only IP addresses:port number that starts with "http ip" as shown below.

It should print :

1.1.1.1:678
1.1.1.4:456

I have tried with following python code:

import re
file_open = open("test.txt", 'r')

for i in file_open:
    if re.findall(".*http(.*)",i):
        print i[0]  

If I run the above python code, it prints :

2
2
2

Any idea to fix this please?

Upvotes: 1

Views: 943

Answers (1)

user3657941
user3657941

Reputation:

Try this:

import re
file_open = open("test.txt", 'r')

for i in file_open:
    result = re.match('.*(http ip : )([0-9:.]+)', i)
    if result:
        print result.group(2)

For test.txt with these contents

this is the http ip : 1.1.1.1:678 blah blah.com2
this is the https ip : 1.1.1.2:654 blah blah.com2
this is the http ip : 1.1.1.4:456 blah blah.com2
the sever this is the http ip : 1.1.1.4:456 blah blah.com2

This is the output:

1.1.1.1:678
1.1.1.4:456
1.1.1.4:456

Upvotes: 2

Related Questions