【问题标题】:How to add multiple lines after a specific pattern or line number in a linux file within python envirnoment如何在python环境中的linux文件中的特定模式或行号之后添加多行
【发布时间】:2018-11-27 10:53:00
【问题描述】:

对于在 linux shell 中执行下面的 SED 命令,我没有问题。但是要在 python-2 环境中运行它,我有问题。

我想在 HTML linux 文件中的 href=part1 行之后添加以下行。

CMDD = "sed -i '/href=part1/a \n\t\t<tr>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t</tr>' /root/var/www/html/start/index.html" %(logs[0], logs[1], logs[2], logs[3], logs[4], logs[5], logs[6], logs[7])

res = subprocess.Popen([CMDDD], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

print res

运行后出现以下错误:

('', "sed: -e expression #1, char 18: unknown command: `

我在终端内没有任何问题(例如):

sed -i "/href=part1/a <tr>\n\t\t  <td>AliReza</td>\n\t\t <td>David</td>\n\t\t </tr>" tables.html

【问题讨论】:

    标签: python linux sed


    【解决方案1】:

    您需要通过将r 添加到开头来使命令成为原始字符串,就像这样

    CMDD = r"sed -i '/href=part1/a \n\t\t<tr>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t</tr>' /root/var/www/html/start/index.html" %(logs[0], logs[1], logs[2], logs[3], logs[4], logs[5], logs[6], logs[7])
    

    请记住,python 会将\n 转换为非原始字符串中的文字换行符 (\x0A)。

    【讨论】:

    • 我已经做到了。我得到了不同的错误:('',“sed:无法读取/root/var/www/html/start/index.html:没有这样的文件或目录\n”)。甚至我使用 // 作为路径而不是 /。
    • /root/var/www/html/start/index.html 有文件吗?
    • 是的,文件不是空的。
    • 嗯,听起来像是sed 问题,这不是我的专业领域。无论如何,请继续传递原始字符串。
    • 问题出在路径上。我也忘了在字符串之前使用“r”作为RAW。 TNx你。
    【解决方案2】:

    POpen 的第一个参数应该是命令本身的列表/元组以及命令采用的参数。在您的情况下,这意味着:

    CMDD = [
        "sed",
        "-i",
        r"/href=part1/a \n\t\t<tr>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t  <td>%s</td>\n\t\t</tr>" % (logs[0], logs[1], logs[2], logs[3], logs[4], logs[5], logs[6], logs[7]),
        "/root/var/www/html/start/index.html",
    ]
    res = subprocess.Popen(CMDD, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    print res
    

    正如 FHTMitchell 所说,您还需要使用原始字符串来防止 python 转义特殊字符。

    【讨论】:

    • 我收到了这个错误:('', "Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...\n \n -n, --quiet, --silent\n 禁止自动打印模式空间\n -e script, --expression=script\n
    • 您可以尝试打印 CMDD 以检查它是否符合您的预期,并且没有明显的错误
    • sed -i "/href=part1/a ....... 2018-06-17 70:79: 90:41:62:50 2018-06-17 14:38:19 15:39:29 " /root/var/www/html/start/index.html
    • 有一组额外的[],也许这就是问题所在。
    • 在 CMDD 中使用不同的文件名(例如,我的 PC 上存在的文件名)以上为我运行 sed。
    猜你喜欢
    • 2014-12-28
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多