Kam
Kam

Reputation: 6008

search and replace using python

I have the following file "template.txt"

function FA()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FB()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FC()
{
    if(){...}
    message=[msg]
    message=[msg]
}

I would like to do this:

./script.py --function FB --message TEST

and get this result:

function FA()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FB()
{
    if(){...}
    message=TEST
    message=TEST
}
function FC()
{
    if(){...}
    message=[msg]
    message=[msg]
}

I can now using getopt retrieve all the options and arguments properly but I can't figure out how to achieve the above behavior elegantly. Any ideas? Are there any libraries that can help me with this?

I was able to achieve this behavior using AWK but now I need it in python. In AWK you can go to a specific line (e.g. function FC()) and start replacing from there until you hit another function. I can't seem to figure this out in python.

I am also wondering if there's a better approach to this problem.

Upvotes: 1

Views: 92

Answers (1)

James Robinson
James Robinson

Reputation: 822

Once you get your variables, and have them sanitized properly you can do something like this.

def templater(template,function,message):
    template = template.split('function')
    for i,f in enumerate(template):
        if function in f:
            template[i] = f.replace('[msg]',message)
    return 'function'.join(template)

Edit: As far as a better approach, you should consider creating your template using the formatting mini language http://docs.python.org/2/library/string.html#formatspec or an actual templating language such as jinja2 http://jinja.pocoo.org/docs/

Upvotes: 1

Related Questions