如何从java代码运行sed命令

我可能遗漏了一些东西,但我正试图从java运行命令行

代码如下:

String command = "sed -i 's/\\^@\\^/\\|/g' /tmp/part-00000-00000"; ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); Process process = pb.start(); process.waitFor(); if (process.exitValue() > 0) { String output = // get output form command throw new Exception(output); } 

我收到以下错误:

  java.lang.Exception: Cannot run program "sed -i 's/\^@\^/\|/g' /tmp/part-00000-00000": error=2, No such file or directory 

fils存在。 我正在这个文件上做它并且它存在。 我只是想找到一种方法让它在java中运行。 我究竟做错了什么?

将命令作为数组传递,而不是字符串:

 String[] command={"sed", "-i", "'s/\\^@\\^/\\|/g'", "/tmp/part-00000-00000"}; 

请参阅ProcessBuilder文档。

老实说,在这种情况下不需要外部执行sed 。 用Java读取文件并使用Pattern 。 然后你有可以在任何平台上运行的代码。 将它与org.apache.commons.io.FileUtils结合使用,您可以在几行代码中完成。

  final File = new File("/tmp/part-00000-00000"); String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8.name()); contents = Pattern.compile("\\^@\\^/\\").matcher(contents).replaceAll("|"); FileUtils.write(file, contents); 

或者,在一个简短,独立,正确的例子中

 import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; public final class SedUtil { public static void main(String... args) throws Exception { final File file = new File("part-00000-00000"); final String data = "trombone ^@^ shorty"; FileUtils.write(file, data); sed(file, Pattern.compile("\\^@\\^"), "|"); System.out.println(data); System.out.println(FileUtils.readFileToString(file, StandardCharsets.UTF_8)); } public static void sed(File file, Pattern regex, String value) throws IOException { String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8.name()); contents = regex.matcher(contents).replaceAll(value); FileUtils.write(file, contents); } } 

它给出了输出

 trombone ^@^ shorty trombone | shorty 

尝试

 Process p = Runtime.getRuntime().exec("sed -i 's/\\^@\\^/\\|/g' /tmp/part-00000-00000");