在Groovy中执行Unix的cat命令?

3

你好

我想要在Groovy程序中执行类似于cat /path/to/file1 /path/to/file2 > /path/to/file3的命令。我尝试了"cat /path/to/file1 /path/to/file2 > /path/to/file3".execute(),但是这并没有起作用。

经过一些搜索,我了解到了sh -c的使用方法。因此,我尝试了"sh -c cat /path/to/file1 /path/to/file2 > /path/to/file3".execute(),但还是没有成功。

你有什么建议吗?

2个回答

4

我相信您需要使用List.execute()方法在Shell中运行此程序,即:

[ 'sh', '-c', 'cat file1 file2 > file3' ].execute()

或者,您可以使用Groovy的方式来实现。
new File( 'file3' ).with { f ->
  [ 'file1', 'file2' ].each { f << new File( it ).asWritable() }
}

1
太棒了,谢谢!你能否解释一下为什么我们必须使用List.execute()方法而不是标准的String.execute()方法吗? - th3morg

1

也许您需要提供可执行文件的完整路径?"/bin/sh -c '/bin/cat file1 file2 >file3'".execute()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接