Last active
July 12, 2023 07:45
-
-
Save za/0b1123d029d204a597949589eea189bc to your computer and use it in GitHub Desktop.
Extract IP address from a text file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipaddress | |
import re | |
import sys | |
def extract_ip_addresses(lines): | |
ip_addresses = [] | |
for line in lines: | |
words = line.split() | |
for word in words: | |
word = re.sub('"', " ", word) | |
word = word.strip() | |
try: | |
ip = ipaddress.ip_address(word) | |
ip_addresses.append(ip) | |
except ValueError: | |
pass | |
return ip_addresses | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
filename = sys.argv[1] | |
with open(filename, 'r') as file: | |
lines = file.readlines() | |
ips = extract_ip_addresses(lines) | |
for ip in ips: | |
print(ip) | |
else: | |
lines = sys.stdin.readlines() | |
ips = extract_ip_addresses(lines) | |
for ip in ips: | |
print(ip) |
Pipeline support:
➜ $ grep ciao voila.csv | python3 extract.py
202.142.99.0
203.188.3.9
with voila.csv
➜ findip head voila.csv
no, name, description
1, ciao, 202.142.99.0
2, chiko, 202.143.98.1
3, ciao, 203.188.3.9
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage with
sample.txt
file: