python regex help

Associate
Joined
23 Mar 2006
Posts
1,739
Evening all,

I'm after a bit of help with python regular expressions.

I want to search a file for an IP address, then put a # at the start of the next two lines. Being able to do the reverse would be good too (but I'm sure I could figure that out if I had the first bit).

Thanks
 
I wouldn't say a regex is your best option here.

I would read the file line by line and write it out line by line. If the IP address appears in the current line you would set a flag and prepend the following two lines with # before writing them out.

Just knocked this up, works fine for me but could be tidied up a bit more :)

Code:
#!/usr/bin/python3
import fileinput

ipAddr = "127.0.0.1"
fileName = "logs.txt"
commentCount = 0
numComments = 2

for line in fileinput.FileInput(fileName, inplace=1):
	
	if ipAddr in line:
		commentCount = numComments
	
	elif commentCount != 0:
		line = line.replace(line, '#' + line)
		commentCount = commentCount - 1
		
	print(line, end='', sep='')
 
Last edited:
Thanks for the help, that seems like a reasonable way of doing it.

I am however having some problems with that, I get an invalid syntax error for the print line (in particular the = of end='' ). That the one line that I'm not sure what it's there for. If I don't have it then the file is empty after running the code.

If it makes any difference I am using python 2.7 not 3.
 
For python 2.x, add import sys to the top, and replace the print line with sys.stdout.write(line):

Code:
import sys
...
sys.stdout.write(line)

Inside the for loop, stdout is redirected to the file. So the special print() call I made was required to remove additional new lines (\n) that python usually auto outputs when you use print(). In python 2 the same can be achieved by using sys.stdout.write :)
 
Last edited:
Back
Top Bottom