How to evaluate IP addresses in a file using Python?

I have a log file containing some Whois entries with relative IPs that I want to censor: 81.190.123.123c 81.190.xxx.xxx.

Is there any way to do this conversion and overwrite the contents of the file without changing the rest?

Thanks for the help!

+5
source share
3 answers

As mentioned above, you can do this with sed:

sed -E -e 's/([0-9]+\.[0-9]+)\.[0-9]+\.[0-9]+/\1.xxx.xxx/g'

This uses regex to look up IP addresses and replace the last two octets with xxx. Using the switch -i, you can do it all at once:

sed -i.bak -E -e 's/([0-9]+\.[0-9]+)\.[0-9]+\.[0-9]+/\1.xxx.xxx/g' file.txt
+3
source

Python , :

sed -i 's/\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.[0-9]\{1,3\}\.[0-9]\{1,3\}/\1.\2.xxx.xxx/g' mylogfile.log

Perl, :

perl -i -pe 's/(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}/$1.$2.xxx.xxx/g' mylogfile.log

"inline" -i.

0

If you want to use Python, use the fileinput module to process the file or files line by line.

import fileinput
for line in fileinput.input(["filename"], inplace=1, backup='.bak'):
    print processed(line)
fileinput.close()

fileinput with inplace = 1 will rename the input file and read from the renamed file, directing stdout to a new file with the same name. You can use the backup option to prevent the temporary file from being automatically deleted.

If the input signal is important, you need to take care to handle exceptions to prevent loss of input in the event of an error.

0
source

All Articles