I was trying perform replace using sed in VMkernel
. I used the following command,
sed s/myname/sample name/g txt.txt
I got an error saying sed: unmatched '/'
.
I replaced space with \
. It worked.
When I tried the same using python,
def executeCommand(cmd):
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print (output.decode("utf-8"))
executeCommand('sed s/myname/sample\ name/g txt.txt')
I am getting the error sed: unmatched '/'
again. I used \s
instead of space I am getting the name replaced with samplesname
.
How can I replace a string with space?
The simplest thing would be to not be smart about splitting the command:
executeCommand(['sed', 's/myname/sample name/g', 'txt.txt'])
Otherwise you are opening a can of worms, effectively playing a shell parser role.
Alternatively you may run the command in a shell and let the shell parse and run the command:
import subprocess
def executeCommand(cmd):
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
# Or:
# This will run the command in /bin/bash (instead of /bin/sh)
process = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE)
output, error = process.communicate()
print (output.decode("utf-8"))
executeCommand("sed 's/myname/sample name/g' txt.txt")