我正在编写一个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字符。我该怎么解决这个问题?
删除单引号(因为不涉及shell,所以不需要为shell加引号(。
String.execute()
通常不是您想要的,因为它在空白处进行拆分。所以你最好使用["sed", "-i", ... ].execute()
,或者如果你需要shell,使用["sh", "-c", "sed -i '..."].execute()
。