如何从java代码运行sed命令

Jul*_*ias 2 java bash

我可能错过了一些东西,但我正在尝试从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);
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

fils存在.我正在这个文件上做它并且它存在.我只是想找到一种方法让它从java开始工作.我究竟做错了什么?

sud*_*ode 6

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

String[] command={"sed", "-i", "'s/\\^@\\^/\\|/g'", "/tmp/part-00000-00000"};
Run Code Online (Sandbox Code Playgroud)

请参阅ProcessBuilder文档.


Kir*_*rby 6

老实说,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);
Run Code Online (Sandbox Code Playgroud)

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

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这给出了输出

trombone ^@^ shorty
trombone | shorty
Run Code Online (Sandbox Code Playgroud)