python - 查找并替换 POM 中两个单词之间的内容

标签 python bash

需要 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 中的内容

最佳答案

python :

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 "I want this text between the tags"运行

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

相关文章:

json - 如何读取服务状态并通过 bash 中的 JSON 将其传递到 Slack

扫描网络的Linux脚本

python - 如何使用 pil 将没有白色背景(透明?)的 Logo 圆角化?

python - 获取指定函数中调用的所有函数

linux - 如何创建由多个命令组成的别名?

linux - linux 文件搜索中的递归 - Bash 脚本

linux - 为 bash 编写脚本时遇到问题

python - Python 中的可变迭代器?

python - 如何在Holoviews中使用HoloMap查看2D数组切片(Python 3.5.1)

python - 查看哪个 Python 类正在使用我的 100% CPU?