【问题标题】:sed command in Python using json.dumps of a quoted string does not keep the single quote使用带引号的字符串的 json.dumps 在 Python 中的 sed 命令不保留单引号
【发布时间】:2020-07-21 11:29:22
【问题描述】:

对不起,如果标题有点复杂......一个例子会更好地说明我的意思:

我有一个名为 foo 的文本文件,其中包含字符串 'bar'。

在 Python 中,我有一本字典:

d = {"key": "item['id']"}

我想用字典的 json 转储替换文件中的字符串 bar。命令:

import subprocess
subprocess.call("sed 's#bar#%s#g' foo > foo2" % json.dumps(d),shell=True)

当我 cat 文件 foo2 时,结果是:

> cat foo2
{"key": "item[id]"}

问题是:id 周围的单引号丢失了。我怎样才能避免这种情况?

【问题讨论】:

  • 为什么还要尝试使用 sed?全部在 python 中完成。
  • 好吧...也许是因为我认为使用单个 sed 命令会更短。你考虑过 re.sub 吗?
  • 能否分享foo的输入记录
  • @DigvijayS foo = "bar"

标签: python json sed escaping single-quotes


【解决方案1】:

正如@Shawn 所建议的那样,我使用基于 re.sub 的“python sed”函数在 Python 中完成了这一切:

def psed(foo,bar,source,dest):
    """
    implements a python sed, substituting (with multi-line mode) foo for bar 
    in file source, writing the result in file dest
    """
    with open(source,'r') as f:
        content = f.read()
    f.close()
    content_new = re.sub(foo,bar,content,flags=re.M)

    with open(dest,'w') as f:
        f.write(content_new)
    f.close()

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多