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