0

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.

3 Answers 3

1

Regex solution:

You can use the following regex to match:

^(?=@(?!(IP1|IP2)))

And replace with #

See DEMO

Code:

re.sub(r'^(?=@(?!(IP1|IP2)))', r'#', myStr)
Sign up to request clarification or add additional context in comments.

3 Comments

Looks like Fabric doesn't like that syntax. Do I need an import statement?
Looks like if I used that expression with the "re" from below, it accepted the syntax
@Carl_Friedrich_Gauss yes.. you have to use it like with re.. updated the answer :)
0

I would do like,

if not "@IP1" in output or not "@IP2" in output:
    if output.startswith("@"):
        // stuff here

Comments

0

Check if criteria exists in the glob, and if so, open file, read line-by-line, and use re.sub() to add a # inline to the lines that require it.

import re

ip1 = '1.1.1.1'
ip2 = '2.2.2.2'

fh = open('in.txt', 'r')
f = fh.read()
fh.close()

if re.search(r'(@(?!({0}|{1})))'.format(ip1, ip2), f):
    fh = open('in.txt', 'r')
    for line in fh:
       line = re.sub(r'^(@(?!({0}|{1})))'.format(ip1, ip2), r'#\1', line)
       print(line)

Input file:

@1.1.1.1
@this
@2.2.2.2
@3.3.3.3
@
no @
blah

Output:

@1.1.1.1
#@this
@2.2.2.2
#@3.3.3.3
#@
no @
blah

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.