Home > database >  Call a function to replace every regex in a file
Call a function to replace every regex in a file

Time:11-28

I have a some entries in a file and I want to modify specific regex values. This file must remain identical to the original except the value I want to replace.

Here is my file:

dn: uid=alan,cn=users,dc=mysite,dc=dc=com
objectclass: organizationalPerson
objectclass: person
objectclass: top
objectclass: inetOrgPerson
uid: wpsadmin
userpassword: wpsadmin
specificattribute: abc123, cvb765
sn: admin
givenName: fgh876
cn: wps admin
 
dn: uid=alice,cn=users,dc=mysite,dc=dc=com
objectclass: organizationalPerson
objectclass: person
objectclass: top
objectclass: inetOrgPerson
uid: wasadmin
userpassword: wasadmin
specificattribute: def456
sn: admin
givenName: aaa000
cn: was admin

dn: uid=lana,cn=users,dc=mysite,dc=dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
uid: wpsbind
userpassword: wpsbind
specificattribute: ghi789
sn: bind
givenName: wps
cn: wps bind

I want to replace each value like aaa000 by another stored in a dict.

#!/usr/bin/env python3
import re

Dict = {'abc123': 'zzz999', 'cde456': 'xxx888', 'fgh789': 'www777'} # and so on...
def replacement(val):
    val2 = Dict.get(val)
    return print(val2)

I've found a solution to identify the regex but not to call the function named 'replacement'

with open('file.txt', "r ") as f:
    content = f.read()
    content_new = re.sub('[a-z]{3}[0-9]{3}', r'abc123', content)
    f.seek(0)
    f.write(content_new)
    f.truncate()

This code change every matching regex by abc123 but this is not that I want.

CodePudding user response:

You can try the following:

with open('file.txt', 'r') as f:
    content = f.read()

for old_value, new_value in Dict.items():
    content = content.replace(old_value, new_value)

with open('file.txt', 'w') as f:
    f.write(content)
  • Related