0

SED command is not executing when I'm trying it to execute with Java, while it is getting executed successfully manually. No response & no error is seen in output.

My SED Command: Manually:

sed -i 's/abc/xyz/' /home/tmp.txt

In java file:

String[] cmdtest = {"sed ", "-i","'s/abc/xyz/'"," /home/tmp.txt"};

Process:

StringBuffer output = new StringBuffer();
Process p = null;
try {
    p = Runtime.getRuntime().exec(cmdtest);
    p.waitFor();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
    }

} catch (Exception e) {
        e.printStackTrace();
}

3 Answers3

2

You first waitFor the process to end, then proceed to read its output. You must take the output while the process is running; otherwise its output buffer will fill up and then the process will block until you drain it. So just remove waitFor and it will start working.

Further, beyond the Java aspect of this question, I see problems in how you have constructed the command line:

{"sed " + "-i","'s/abc/xyz/'"," /home/tmp.txt"}
  1. the first element is "sed -i"—obviously you meant for -i to be the first argument, not a part of the command name.
  2. you have '...' around the second argument: this will be passed literally to sed, making it an invalid command specification. Quotes are only needed at the shell prompt.
  3. The last argument has an extra space in front, which could lead to problems as well.
  4. Calling sed with -i orders it to make changes to the file in-place, producing no output at all.

So probably you wanted instead

{"sed", "s/abc/xyz/", "/home/tmp.txt"}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

The line

 String[] cmdtest = {"sed " + "-i","'s/abc/xyz/'"," /home/tmp.txt"};

is faulty.

  • The name of the program you want to runs is sed, not sed-i.
  • The SED script you want to run is s/abc/xyz/, not 's/abc/xyz/' (note the quotes).
  • The path-name of teh file you want to edit is /home/tmp.txt, not /home/tmp.txt (note the extra space).

Try this:

 String[] cmdtest = {"sed", "-i","s/abc/xyz/","/home/tmp.txt"};
Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • thanks that worked, can you tell me how to use / also in commands. thanks in advance – user3356868 Aug 28 '15 at 14:52
  • @user3356868 It seems we have answered your original question. If you have a separate question, [ask it as a *separate* question](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions). – Raedwald Aug 28 '15 at 14:55
0

raedwald & marko gave correct answers. use

String[] cmdtest = {"sed", "-i","s/abc/xyz/","/home/tmp.txt"};

thanks