1

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

1 Answer 1

4

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())
Sign up to request clarification or add additional context in comments.

5 Comments

thank you tim for your Quick response what to do if i want to delete the data between cmd only if it contain 'xcopy' string
Note that this won't properly process nested <cmd> tags, but it doesn't look you need to so it should be fine.
Hi Tim Pietzcker one more doubt.For some case i have to match XCOPY.ie i have to do above process for both XCOPY and xcopy.I tried with re.IGNORECASE but it didn't worked
Use (?isx) instead of (?sx) at the start of the regex.
ohh great you are really a regex guru.Thank you.If you don't mind please suggest some topics for regex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.