查找与表达式匹配的行,复制整行,插入新行并替换表达式

时间:2018-11-07 22:46:28

标签: awk sed

我有几个文件(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)

1 个答案:

答案 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)

一个警告是文件的最后一行有一个匹配项,迭代器会错过这一点。