1

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?

Kajal
  • 709
  • 8
  • 27
  • split() by default splits by space... so of course you'll have issues... with `\s` python string acts up... use `r'string'` format instead – Sundeep Jul 14 '17 at 06:35
  • Quoting. In the shell: `sed 's/myname/sample name/g' txt.txt` In python: `executeCommand('sed s/myname/sample\\ name/g txt.txt')` (extra backslash) - untested. – cdarke Jul 14 '17 at 06:35
  • By using `split()` you are sending the list `['sed', 's/myname/sample\', 'name/g', 'txt.txt']` to subprocess. The sed expression is split in half. It's better to create the list yourself, so you have full control. – Håken Lid Jul 14 '17 at 08:00

1 Answers1

2

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")
hek2mgl
  • 152,036
  • 28
  • 249
  • 266