I'm using Python Fabric, trying to comment all lines in a file that begin with "@", unless that "@" is followed by 2 specific IP addresses. So if the file contains (without the bullets)
- @hi
- @IP1
- some stuff here
- @IP2
then the resulting file should be (also without the bullets)
- #@hi
- @IP1
- some stuff here
- @IP2
This is what I have so far:
def verify():
output = sudo("/sbin/service syslog status")
#if syslog is running
if 'is running...' in output:
#then set output to the value of the conf file
output = sudo("cat /etc/syslog.conf")
#If pattern is matched
if "@" in output and not "@IP1" and not "@IP2":
#read all the lines in the conf file
sys.stdout = open('/etc/syslog.conf', 'r+').readlines()
#and for every line, comment if it matches pattern
for line in sys.stdout:
if "@" in line and not "@1P1" and not "@IP2":
line = "#" + line
else:
print GOOD
else:
print RSYSLOG
I get that when I say
if "@" in output and not "@IP1" and not "@IP2"
Python is thinking that I am saying "do some thing if there is an @ in the file, but ONLY if you also do not have @IP1 and @IP2." What I'm trying to say is "do some thing to any line starting with an @, except the lines @IP1 and @IP2." Also I know there are other errors in my code, but I'm working on just this now.
thanks.
Regex solution:
You can use the following regex to match:
And replace with
#
See DEMO
Code: