1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks so much for your answer. Its works. Actually I want grep IP that starts with "http ip :". Any idea on this please?
I changed it to include the "http ip :". Is this what you are looking for?
Sorry for the confusion. I dont want to print "http ip : IP:port". Actually I wanted to grep the string(IP:port), that starts with "http ip:". For example, If I have a line "this is the https ip : 2.1.1.1:678 blah blah.com2", It should not print this IP. I hope now I am clear in my question. Sorry again for the confusion.
I changed it to use a regular expression to handle the "http ip :".
Actually its prints nothing. I mean I am NOT getting any output. Could you please check once?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.