I have a script, which I want to use to remove a line that contains a specific IP address from a file. This is:
for line in fileinput.input(hostsFileLoc,inplace =1):
line = line.strip()
if not hostIP in line:
print line
This sort of works, however, there are two things I am trying to work out.
-
This script will remove any matches, so in example before
127.0.0.1
127.0.0.11
127.0.0.111
192.168.0.1If I run this with the input of “127.0.0.11”, it will remove both “127.0.0.11” and “127.0.0.111”, which is not what I want.
-
This script doesn’t handle csv files either. I need to remove it from a file where each line is just and IP address per line, as per the list above, and also a csv file where the first field is the offending IP address. I have tried using the regex
[\s\,]+in the strip function, but this doesn’t work correctly and adds a blank line when it reprints the remaining lines back to file.
I know this may be a lot to ask, but I am still trying to find my way around the wonders of Python.
You just need to be more specific in your test. For the first example test that the whole line (after a strip) is equal to the ip address (stricter than that it contains it – thus working around your first issue). For the second, split each line on the comma character, and test that the first element is equal to your IP address string.
So for the first file type:
And for the csv file type: