-3

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
PsyKoptiK
  • 35
  • 1
  • 8
  • 2
    Actually, you can pass callable to [`re.sub()`](https://docs.python.org/3/library/re.html#re.sub), it will receive [`re.Match`](https://docs.python.org/3/library/re.html#re.sub) object in first argument. It could be simple `lambda`: `re.sub(r'[a-z]{3}\d{3}', lambda m: your_dict.get(m[0]), content)` – Olvin Roght Nov 26 '22 at 21:00
  • Theres a function in Python called `replace()` that you could use instead. No need to complicate with regex unless that's a requirement. – Sandsten Nov 26 '22 at 21:02
  • 1
    To add on @OlvinRoght 's comment: content_new = re.sub('([a-z]{3}[0-9]{3})', lambda m: Dict.get(m[0],m[0]), a) will replace the codes if they appear in the Dict and leave them untouched if not. – Swifty Nov 26 '22 at 21:10
  • Additionnally, the validated answer to this post compares severals ways to replace multiple substrings in a string: https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string – Swifty Nov 26 '22 at 21:16
  • Thanks for your comments, lambda is indeed very useful. – PsyKoptiK Nov 27 '22 at 08:08

1 Answers1

0

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)
JMA
  • 803
  • 4
  • 9