Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run sed command from java code

Tags:

java

bash

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?

like image 270
Julias Avatar asked Jun 24 '26 16:06

Julias


2 Answers

Pass the command as an array, not a string:

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

See ProcessBuilder documentation.

like image 174
sudocode Avatar answered Jun 27 '26 07:06

sudocode


Honestly there is no need to externally execute sed in this case. Read the file in Java and use Pattern. Then you have code that could run on any platform. Combine this with org.apache.commons.io.FileUtils and you can do it in a few lines of code.

Alternatively, you could use java.util.Scanner to avoid loading the whole file into memory.

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

Or, in a short, self-contained, correct example

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

which gives output

trombone ^@^ shorty
trombone | shorty
like image 25
Kirby Avatar answered Jun 27 '26 08:06

Kirby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!