Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a function block in a file using python

Tags:

python

regex

I have a Ruby function code block in multiple files that I need to change in each file.

The function that I am trying to replace looks something like this:

    def func1 options
        ...
        some code here
        ...
        def inner_func1 inner_options
            ...
            some code here
            ...
        end
        ...
        some more code here
        ...
    end

Each file has other functions in it but with different names. In some files I may have multiple tabs or spaces before.

I want to replace the func1 in each file with contents reading from another file (which can be a variable passed in the parameter).

So far I have written this following python function for one such file to change:

import re

a = open('main.rb').read() # file where I have the func1
b = open('modified.rb').read() # file where I have only the modified func1 

c = re.sub('(^[ \t]*)def func1:$.?\1end$',b,a, flags=re.DOTALL)

print(c)

with open('main.rb', 'w') as filetowrite:
    filetowrite.write(c)
        

However my c string does not show there was a change to anything.

I am not sure if there is anything wrong with my regex.

like image 270
user1422576 Avatar asked Nov 06 '22 05:11

user1422576


1 Answers

Please try below regex

(?:^|\n)([\t ]*?)def func1 options[\s\S]*?\n\1end

Code

import re

input="""
def func1 options
    some code here
    def inner_func1 inner_options
        some code here
    end
    some more code here
end
"""

replacement="""
def new_func1 options
    new code here
end
"""

print(re.sub(r"(?:^|\n)([\t ]*?)def func1 options[\s\S]*?\n\1end",replacement,input),end='')

Output

def new_func1 options
    new code here
end

Regex demo | Python demo

like image 200
Liju Avatar answered Nov 14 '22 22:11

Liju