0

I have shell file test.sh and it has following data in it:-

export HOME=/some/path/to/directory

export VERSION=89

export CONNECTION=database_connection

Now I want to update the values HOME, VERSION and CONNECTION in the shell script file using python. How can I do this in python?

2
  • Please specify whether you want to modify the shell script via Python or whether you need to use these variables in a Python script but set different values? Commented Jun 12, 2014 at 6:36
  • Using python I just want to modify values in shell file. Commented Jun 12, 2014 at 6:43

2 Answers 2

1

You can achieve this with simple search and replace

re.M is used for multiline

import re

s = open('test.sh', 'r').read()

s = re.sub(r"^export HOME=.*$", "export HOME=/new/path", s, 0, re.M)
s = re.sub(r"^export VERSION=.*$", "export VERSION=new_version", s, 0, re.M)
s = re.sub(r"^export CONNECTION=.*$", "export CONNECTION=new_connection", s, 0, re.M)

open('test.sh', 'w').write(s)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.