Reputation: 5492
is there any way to update multiple lines of a textfile using python.I want to delete the data between two lines My text file is as follows
Project
Post
<cmd> ---Some statements--
---Some statements---
Mycommand "Sourcepath" "DestPath"
</cmd>
Post
Lib
TargetMachine=MachineX86
Lib
Project
Post
<cmd> ---Some statements---
---Some statements---
Mycommand "Sourcepath" "DestPath"
</cmd>
Post
Lib
TargetMachine=MachineX64
Lib
I want to delete everything between cmd tag.So that the resulting text file should be as follows
Project
Post
<cmd>
</cmd>
Post
Lib
TargetMachine=MachineX86
Lib
Project
Post
<cmd>
</cmd>
Post
Lib
TargetMachine=MachineX64
Lib
Upvotes: 1
Views: 337
Reputation: 336248
Assuming you can read the entire file into memory at once, I'd suggest
import re
with open("input.txt") as infile, open("output.txt", "w") as outfile:
outfile.write(re.sub(r"(?s)<cmd>.*?</cmd>", "<cmd>\n</cmd>", infile.read()))
To only match tags that have xcopy
in them, you need to expand the regex a little:
import re
with open("input.txt") as infile, open("output.txt", "w") as outfile:
outfile.write(re.sub(
r"""(?sx)<cmd> # Match <cmd>.
(?: # Match...
(?!</cmd>) # (unless we're at the closing tag)
. # any character
)* # any number of times.
\bxcopy\b # Match "xcopy" as a whole word
(?:(?!</cmd>).)* # (Same as above)
</cmd> # Match </cmd>""",
"<cmd>\n</cmd>", infile.read())
Upvotes: 4