How to run sed command from java code

I probably missed something, but I'm trying to run a command prompt from java

The code is as follows:

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 get the following error:

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

Fleurs exist. I do this in this file and it exists. I'm just looking for a way to make it work from java. What am I doing wrong?

+2
source share
3 answers

Pass the command as an array, not a string:

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

See the ProcessBuilder documentation .

+5
source

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

, , ,

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

trombone ^@^ shorty
trombone | shorty
+3

Try

Process p = Runtime.getRuntime().exec("sed -i 's/\\^@\\^/\\|/g' /tmp/part-00000-00000");
-1
source

Source: https://habr.com/ru/post/1679619/


All Articles