Home > Software engineering >  sed gives unknown command error: char 1: unknown command: `''
sed gives unknown command error: char 1: unknown command: `''

Time:09-29

i am trying to use sed to do some text processing in a file called host

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

Then I am calling it like this

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

But i am getting this error:

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

Could someone please explain me what am I doing wrong? Thank You

I also tried using fileinput but i am unable to print print(f"{cluster_ip}\t{srv_domain}\n") to the file instead this is going to the console.

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()

CodePudding user response:

I suppose you want to remove the first line and add a last line. You don't need to protect arguments, it's already done by the subprocess module. so you're getting the quotes literally.

quickfix:

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

better: learn to use python to avoid calling sed in your script and make them complex and non portable. You don't even need regexes here, just substring search (which could be improved with regexes to avoid substring match but the problem is already present in the original expression)

First read your file, drop the line where srv_domain is defined, and add your last line.

Something like this, using a temporary file to hold the modified contents, then overwriting it:

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")
  • Related