简体   繁体   中英

How to replace unique string between two separators/strings multiple times

I am walking through a folder/directory and reading all files, checking if there is a certain tag, then replacing a specific string multiple times only when it is in between two certain strings/tags. Here is an example of the text files:

START $YES
N1 000 001 002
N2 TAG#1 004 008
N3 This is an apple
N4 006 005 003
(( TAG#2 ))
N5 This is an apple

I would like a solution that can open the files, check if START $YES or START $NO , and replace the string This is an apple into There is no apple in between TAG#1 and TAG#2 only if START $YES is present. I would prefer the original file to be left unaffected (create a new file or create a backup using the fileinput library).

I cannot post my python code at the moment, but I will update this post when I am back at my work desk with the code that I have attempted.

import shutil

def func(srcname, dstname):
    replace = False
    with open(srcname) as srcfile:
        with open(dstname, 'w+') as dstfile:
            line = srcfile.readline().strip()
            if "START $NO" in line:
                srcfile.seek(0)
                shutil.copyfileobj(srcfile, dstfile)
                return
            while line:
                if "TAG" in line and not replace:
                    replace = True
                if "TAG" in line and replace:
                    replace = False
                if replace and "This is an apple" in line:
                    line = line.replace("This is an apple", "There is no apple")
                dstfile.write(line)
                line = srcfile.readline().strip()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM