0

I am getting a IOException when trying to run a sed command through Java using a ProcessBuilder:

ERROR: java.io.IOException: Cannot run program "sed -i 's/hello world//g' 
/home/user/test": error=2, No such file or directory

The command is sed -i 's/hello world//g' /home/user/test But the problem isn't the command, I can run the same command through terminal and it would remove the string "hello world"

public void removeString(String str, String file) throws IOException {
    String command = "sed -i \'s/" + str + "//g\' " + file;
    System.out.println(command);
    ProcessBuilder pb = new ProcessBuilder(command);
    Process p = pb.start();
}

What is causing the process to be unable to find the file?

1
  • you could try to run the sed binary using its full path. Commented Mar 26, 2013 at 20:58

1 Answer 1

4

ProcessBuilder expects individual arguments to be sent separately in the constructor. Try running it like this:

ProcessBuilder pb = new ProcessBuilder("sed", "-i", "s/hello world//g", "/home/user/test");

(You can also pass it a List<String> if you want)

It works this way to prevent shell injection security vulnerabilities.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.