python - sed 在 python 中带有空格

标签 python sed vcenter

我尝试在 VMkernel 中使用 sed 执行替换。我使用了以下命令,

sed s/myname/sample name/g txt.txt

我收到错误消息 sed: unmatched '/'。 我用 \ 替换了空格。它起作用了。

当我使用 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')

我再次收到错误 sed: unmatched '/'。我使用 \s 而不是空格,我将名称替换为 samplesname

如何用空格替换字符串?

最佳答案

最简单的事情就是不明智地拆分命令:

executeCommand(['sed', 's/myname/sample name/g', 'txt.txt'])

否则,您将打开一堆蠕虫,有效地扮演 shell 解析器的角色。

<小时/>

或者,您可以在 shell 中运行该命令,并让 shell 解析并运行该命令:

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

关于python - sed 在 python 中带有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45096181/

相关文章:

python - Django admin 额外字段 Sum() TimeField

python - 抛出空白偶数页/左页

shell - SED 或 AWK 全部替换为另一个文件中的模式

java - 获取无法生成DH key 对异常

c# - HttpWebrequest 失败,内部异常身份验证失败,因为远程方已关闭传输流

python - 最Pythonic条件计数器

从磁盘加载的 Python 字典占用太多内存空间

regex - sed/awk : replace megabytes with bytes (insert zeros)

regex - "sed"特殊字符处理

rest - VCenter:REST API:如何将 ova 上传到内容库