Skip to content
Advertisement

How to modify specific line in sql file?

I am trying to modify a line in sql file in a directory. Currently have written the code which navigates to files directory according to user input .

each sql file in that dir has these 2 lines:

--liquibase formatted sql
--changeset Jack:1 runOnChange:true splitStatements:false stripComments:false

I am trying to do is loop through all files and I want to change-set every-time the script runs.

so those 2 lines will look like this :

 --liquibase formatted sql
 --changeset Ryan:2 runOnChange:true splitStatements:false stripComments:false

The part I want to change in line is constant but the content is different for each file like in other file it will be Jie:6 I want to replace that with Priyal:7. So the name part is the person who is running the script and the number after : is incremented

Is there a cleaner way to achieve this :

This is just sample code I have which configures path and everything :

anbpath = os.path.abspath("copy_views.py")
 print(anbpath)

sqldir = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'database')) 

path_to_views = sqldir+"/sql/edm/changes/"+source_release_version+"/mutable/view"
print(path_to_views)


destdir = os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..', 'database')) 

path_to_dest_rel_ver = destdir+"/sql/edm/changes/"+dest_release_version

path_to_dest = path_to_dest_rel_ver+"/mutable/view"

I will traverse all files in path_to_dest using os.walk

Advertisement

Answer

If your file is called “file.txt” and if the name is constant then what you are looking for is

# Read the contents of file
with open("file.txt", 'r') as fp:
    lines = fp.readlines()

#Idendify tokens and numbers with in them and increment them
words = lines[1].split()
tokens = words[1].split(":")
words[1] = "name{0}:{1}".format(int(tokens[0][4:])+1, int(tokens[1])+1)
lines[1] = ' '.join(words)

# Write back the updated lines
with open("file.txt", 'w') as fp:
    fp.writelines(lines)

Initial content of file

"--liquibase formatted sql", "--changeset name3:21 runOnChange:true splitStatements:false stripComments:false"]

Afer modification

"--liquibase formatted sql", "--changeset name4:22 runOnChange:true splitStatements:false stripComments:false"]

However, if the name is not constant then we can still split the token at “:” to indentify the number after “:” but to indentify the number ending at the name we will have to use regex.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement