Link to home
Start Free TrialLog in
Avatar of MarkLoveExEx
MarkLoveExEx

asked on

Java "sed" substitute command

Taking the following linux sed command:

sed 's/Q3A01RAD/MPM01   /' name > temp.file

What would be an equivalent way to accomplish this using Java code?
ASKER CERTIFIED SOLUTION
Avatar of Jim Cakalic
Jim Cakalic
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dpearson
dpearson

Something like this will get you started:

String line;
// Read the file
try (BufferedReader input = new BufferedReader(new FileReader(file))) {
    while ((line = input.readLine()) != null) {
         // Do the string replacement
         line = line.replace("Q3A01RAD","MPM01   ");

         // Print out the result
         System.our.println(line) ;
    }
}

Open in new window


Doug
Something like this will get you started:
In point of fact, you posted something implementing

 's/Q3A01RAD/MPM01   /g'

Open in new window


To implement the given pattern, you'd need String.replaceFirst
Good catch CEHJ!

Doug
Avatar of MarkLoveExEx

ASKER

Jim Cakalic -- I like the idea of using unix4j. However, I'm trying to figure out how to get it in my RedHat Eclipse IDE. Is there a compiled jar out there somewhere that I can add to my build path to get access to the functionality and have intellesense to help me formulate the syntax?
Would you trust this site to get the unix4j jars?
http://www.java2s.com/Code/Jar/u/unix4j.htm

I would assume I would just add those to my class path...
Ok. I figured out how to use unix4j in my java code. Unfortunately, the file that I am attempting to use as input is a BINARY file.  Command-line sed worked on my binary file, but the unix4j routine seems to have trouble with it (the binary file got larger/corrupted. Any ideas?
sed is normally used on text files (it works line-wise) so the Java implementation might not expect to have to be able to work with binary files
CEHJ -- yes, I am very lucky that sed works on these particular binary files that I apply it on.
I'm not sure you can rely on the continuance of that