【问题标题】:groovy String not executing with .execute() the same way it does on command linegroovy String 与 .execute() 的执行方式与在命令行上的执行方式相同
【发布时间】:2020-03-31 18:34:35
【问题描述】:

我正在编写一个 groovy 方法来从文件中删除换行符。

def removeEmptyLines(filePath){
    cmd="""sed -i '/^\$/d' ${filePath}
    """
    println cmd
    result = cmd.execute()
    result.waitFor()
    println result.exitValue()
}
removeEmptylines("/path/to/file.txt")

我的输出是:

sed -i '/^$/d' /path/to/file.txt
1

文件保持未编辑状态,显然退出状态非零。 但是,如果我从字面上将第一个输出复制并粘贴到命令行中,它就可以工作。我正在使用绝对路径。

我的猜测是 groovy 不喜欢我的命令中的正则表达式字符。我该如何解决这个问题?

【问题讨论】:

    标签: regex bash groovy


    【解决方案1】:

    去掉单引号(shell不需要加引号,因为不涉及shell)。

    String.execute() 通常不是您想要的,因为它在空白处拆分。所以你最好使用["sed", "-i", ... ].execute(),或者如果你需要shellisms,使用["sh", "-c", "sed -i '..."].execute()

    【讨论】:

    • 这是一个很好的答案!但是我将如何在 groovy 的 shell 中运行一些东西呢?例如,有时我需要使用更长的线。
    猜你喜欢
    • 2022-08-06
    • 2016-05-25
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 2013-04-29
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多