How to run sed command from java code

Tags: ,



I’m probably missing something, but I’m trying to run commandline from a java

The code is as following:

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);
}

I’m getting the following error:

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

The fils is exists. I’m doing ll on this file and it is exists. I’m just looking for a way to make it work from java. What am I doing wrong?

Answer

Pass the command as an array, not a string:

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

See ProcessBuilder documentation.



Source: stackoverflow