我有几个文件(yml,tf,xml),需要为它找到一个字符串,即var1,然后用foo2插入新行,其余部分保持不变。 例子
variable "my_vars" {
type = "map"
default = {
var1 = "10.48.225.160/28"
var2 = "10.48.225.160/28"
var3 = "10.48.225.160/28"
var4 = "10.48.225.160/28"
}
}
我尝试了下面的代码,但需要进行适当的编辑。
import sys
import string
def find(substr, replstr, infile):
f = open(infile,"rw")
lines = f.readlines()
for i in range(len(lines)):
if substr in lines[i]:
j = string.replace(lines[i], substr, replstr)
lines.insert(i + 1, j)
print "\n".join(lines)
old_env = sys.argv[1]
new_env = sys.argv[2]
file = sys.argv[3]
find(old_env, new_env, file)
答案 0 :(得分:0)
import sys
import string
def find(substr, replstr, infile):
f = open(infile,"r")
lines = f.readlines()
for i in range(len(lines)):
if substr in lines[i]:
j = string.replace(lines[i], substr, replstr)
lines.insert(i + 1, j)
print "".join(lines)
f.close()
f = open(infile,"w")
k = "".join(lines)
f.writelines(k)
f.close()
old_env = sys.argv[1]
new_env = sys.argv[2]
file = sys.argv[3]
find(old_env, new_env, file)
一个警告是文件的最后一行有一个匹配项,迭代器会错过这一点。