gpt4 book ai didi

python - sed 在 python 中带有空格

转载 作者:行者123 更新时间:2023-12-01 02:47:51 24 4
gpt4 key购买 nike

我尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com