需要bash脚本或python脚本来查找和替换两个标签之间的文本吗?

例如:

<start>text to find and replace with the one I give as input<end>


“查找并替换为我提供的内容的文字”只是一个示例,并且每次都可能有所不同。

我想做类似./changetxt inputfile.xxx newtext的操作

changetxt有脚本;
inputfile.xxx的文本需要更改,而newtext是inputfile.xxx的内容

最佳答案

蟒蛇:

import sys

if __name__ == "__main__":
    #ajust these to your need
    starttag = "<foo>"
    endtag = "</foo>"

    inputfilename = sys.argv[1]
    outputfilename = inputfilename + ".out"
    replacestr = sys.argv[2]

    #open the inputfile from the first argument
    inputfile = open(inputfilename, 'r')
    #open an outputfile to put the result in
    outputfile = open(outputfilename, 'w')

    #test every line in the file for the starttag
    for line in inputfile:
        if starttag in line and endtag in line:
            #compose a new line with the replaced string
            newline = line[:line.find(starttag) + len(starttag)] + replacestr + line[line.find(endtag):]
            #and write the new line to the outputfile
            outputfile.write(newline)
        else:
            outputfile.write(line)
     outputfile.close()
     inputfile.close()


将其保存在replacetext.py文件中,并以python replacetext.py \ path \ to \ inputfile的身份运行“我希望这些文本在标签之间”

关于python - 查找并替换POM中两个单词之间的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9794242/

10-12 17:48