我正在尝试使用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()
发布于 2021-09-28 05:49:32
我想您想要删除第一行并添加最后一行。你不需要保护参数,这已经由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")
https://stackoverflow.com/questions/69356356
复制相似问题