sed gives unknown command error: char 1: unknown command: `''

sed gives unknown command error: char 1: unknown command: `''

我正在尝试使用 sed 在名为 host

的文件中进行一些文本处理
cluster_ip = "10.223.10.21"
srv_domain = "service_domain.svc"
cmd = f"'/^.*{srv_domain}/!p;$a'{cluster_ip}'\t{srv_domain}'"

那我就这样称呼它

subprocess.call(["/usr/bin/sed", "-i", "-ne", cmd,  "host"])

但是我收到这个错误:

/usr/bin/sed: -e expression #1, char 1: unknown command: `''

有人可以解释一下我做错了什么吗? 谢谢

我也尝试过使用 fileinput,但我无法将 print(f"{cluster_ip}\t{srv_domain}\n") 打印到文件,而是转到控制台。

cluster_ip = "123.234.45.5"
srv_domain = "service_domain.svc"
def main():
    pattern = '^.*service_domain.svc'
    filename = "host1"
    matched = re.compile(pattern).search
    with fileinput.FileInput(filename, inplace=1) as file:
        for line in file:
            if not matched(line): # save lines that do not match
                print(line, end='') # this goes to filename due to inplace=1
        # this is getting printed in console 
        print(f"{cluster_ip}\t{srv_domain}\n")

main()

我想你想删除第一行并添加最后一行。您不需要保护参数,它已经由 subprocess 模块完成。所以你得到的是字面上的引号。

快速修复:

cmd = f"/^.*{srv_domain}/!p;$a{cluster_ip}\t{srv_domain}"

更好:学习使用 python 以避免在脚本中调用 sed 并使它们变得复杂且不可移植。你甚至不需要这里的正则表达式,只需要子字符串搜索(可以用正则表达式改进以避免子字符串匹配,但问题已经存在于原始表达式中)

首先阅读您的文件,删除定义 srv_domain 的行,然后添加最后一行。

类似这样,使用临时文件保存修改后的内容,然后覆盖它:

with open("hosts") as fr,open("hosts2","w") as fw:
    for line in fr:
        if not srv_domain in line:
            fw.write(line)
    fw.write(f"{cluster_ip}\t{srv_domain}\n")

os.remove("hosts")
os.rename("hosts2","hosts")