mystack
mystack

Reputation: 5492

Updating multiple lines of a text file python

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

Answers (1)

Tim Pietzcker
Tim Pietzcker

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

Related Questions