You can read the file, and then parse out the tokens. Keep a dictionary with the replacements, and then write the line back to a new file.
import re
exp = r'export (\w+)=(.*?)'
lookup = {'HOME': '/new/value', 'VERSION': 55}
with open('somefile.sh', 'r') as f, open('new.sh', 'w') as o:
for line in f:
if len(line.strip()):
if not line.startswith('#'): # This will skip comments
tokens = re.findall(exp, line.strip())
for match in tokens:
key, value = match
o.write('export {}={}\n'.format(key, lookup.get(key, value)))
else:
# no lines matched, write the original line back
o.write(line)
else:
o.write(line) # write out the comments back
I'll explain the important bits, the rest is just common file writing loops.
The regular expression will result in a list of tuples, each tuple having the matched key and value:
>>> re.findall(r'export (\w+)=(.*)', i)
[('HOME', '/some/path/to/directory'),
('VERSION', '89'),
('CONNECTION', 'database_connection')]
The get() method of dictionaries will fetch a key, and if it doesn't exist, return a default value of None, but you can overwrite the default value to be returned. Exploiting this we have this line:
o.write('export {}={}\n'.format(key, lookup.get(key, value)))
This is saying "if the key exists in the lookup dictionary, return the value, otherwise return the original value from the file", in other words if we don't want to overwrite the value of the key, just write the original value back to the file.