Zack Newsham
Zack Newsham

Reputation: 2992

sed from java gives error

I am trying to use sed to replace the spaces in a file with newlines. This is part of a test suite that needs to be automated, and one of the tools the test suite requires, outputs to a file a space separated list, that needs to be newline separated.

The code I am running looks like this:

  exec = String.format("sed -i 's/ /\\n/g\' %s", filename);
  Process p1 = run.exec(exec);
  results = getOutput(p1.getErrorStream());
  p.waitFor();

the file remains unchanged and results contains this: "sed: -e expression #1, char 1: unknown command:'' "`

the value of exec is: sed -i 's/ /\n/g' /absolute/path/to/file.out and if I run the command from the command line, it works.

Any thoughts on what could be causing this?

Thanks

Upvotes: 1

Views: 620

Answers (1)

pobrelkey
pobrelkey

Reputation: 5973

Replace your first two lines with:

Process p1 = run.exec(new String[]{"sed", "-i", "s/ /\\n/g", filename});

What's going on here: You're trying to call the one-arg version of Runtime.exec(). This doesn't parse your command string into arguments honoring single-quoted or double-quoted strings like a "real" shell would - instead, it just splits on whitespace:

[T]he command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. (Source)

To get the behavior you expect, you'll need to break your command line into arguments yourself, and pass them in as an array.

Upvotes: 2

Related Questions