groovy字符串不使用.execute()执行,与在命令行上执行的方式相同 [英] groovy String not executing with .execute() the same way it does on command line

查看:75
本文介绍了groovy字符串不使用.execute()执行,与在命令行上执行的方式相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一种时髦的方法,用于从文件中删除换行符.

I am writing a groovy method to delete new line characters from a file.

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

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

the file remains unedited and obviously the exit status is non-zero. however, if i literally copy and paste the first output into command line, it works. I'm using absolute paths.

我的猜测是,groovy不喜欢我命令中的正则表达式字符.我该如何解决?

My guess is that groovy doesn't like the regex characters in my command. how do i get around this?

推荐答案

删除单引号(您无需为shell引用,因为不涉及shell).

Remove the single quotes (you dont need to quote for the shell, because no shell is involved).

String.execute()通常不是您想要的,因为它在空格处分割.因此,最好使用 ["sed","-i",...] .execute(),或者如果您需要shellism,请使用 ["sh","-c","sed -i'..."].execute().

String.execute() is usually not what you want, because it splits at whitespace. So you are better off with either ["sed", "-i", ... ].execute() or if you need shellisms use ["sh", "-c", "sed -i '..."].execute().

这篇关于groovy字符串不使用.execute()执行,与在命令行上执行的方式相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆