Using ConfigParser to delete lines in config file with no sections

976 views Asked by At

I am trying to change a .conf file on a Linux server, but there are no sections in the .conf file. I want to search in a key/value pair for a specific keyword and then delete a couple of lines above that line and some lines below that line.

How do I go about achieving this when there are no section headers? Should I even be using ConfigParser?

Also, there are repeating key names throughout the file. In the code section below, I want to search for 'keyword' in the "directory" line and the delete two lines above and the rest of the stuff below that.

database        ldbm
loglevel        0
directory       /home/name/NameServer/var/openldap-ldbm-CMDB-keyword
suffix          "o=CMDB-keyword"
suffix          "dc=CMDB-keyword,dc=com"
rootdn          "cn=admin,o=CMDB-keyword"
rootpw          (blahblah)
schemacheck     on
lastmod         off
sizelimit       100000
defaultaccess   read
dbnolocking
dbnosync
cachesize       100000
dbcachesize     100000000
dbcacheNoWsync
index objectclass pres,eq                                                      │
index default pres,eq                                                          │
index termName pres,eq
1

There are 1 answers

0
iruvar On

Assuming that each block starts with the database line and ends with the index termName pres,eq line, this scripts reads from input.conf and writes those blocks to output.conf that do not contain the directory....keyword line

import re
with open('input.conf') as f, open('output.conf', 'w') as o:
    s = f.read()
    for x in re.findall(r'^database.*?index termName pres,eq\n', s, 
     re.DOTALL | re.MULTILINE):
            if not re.search(r'^directory.*keyword', x, re.MULTILINE):
                    o.write(x)