Sep-08-2022, 06:57 AM
(Sep-06-2022, 09:36 PM)Gman2233 Wrote: Then, I want to read this file and add line comments.. '--' to the beginning if each line in the original DDL script (A different file) that adds the erroneous constraints:
ALTER TABLE "TABLE" MODIFY ("PK" NOT NULL ENABLE)
~becomes~
-- ALTER TABLE "TABLE" MODIFY ("PK" NOT NULL ENABLE)
Why write a script to do this at all? If you're using this to learn Python, that's fine, but do be aware that there are often other tools that can help. In this case, at least on Unix*, I'd use
sed
. Assuming the file is called changes.sql
:Output:$ cat changes.sql
ALTER TABLE "TABLE" MODIFY ("PK" NOT NULL ENABLE)
$ sed -i .original 's/^/--/' changes.sql
$ cat changes.sql
--ALTER TABLE "TABLE" MODIFY ("PK" NOT NULL ENABLE)
$ cat changes.sql.original
ALTER TABLE "TABLE" MODIFY ("PK" NOT NULL ENABLE)
So, to break down what the sed
command does here:- The
-i
option will modify the file in place, but leave the original in a file whose name has the given extension (.original
here).-
's/^/--/'
specifies what we want sed
to do - substitute the beginning of the line (i.e. the regular expression ^
) with the comment characters --
. It will do this for each line.Printing out the file shows that the line has been changed and printing out the one with
.original
on the end shows we've indeed kept the original there.A good tutorial on
sed
can be found here: https://www.grymoire.com/Unix/Sed.html.Note also that text editors are powerful these days and have useful search and replace functionality, so you may choose to do it that way.
* I don't use Windows, so I don't know what the options are there.