I want to run grep command from java.
Here is what I had tried. Please let me know, why it is not displaying ouput.
public static void main(String args[]) throws IOException{
Runtime rt = Runtime.getRuntime();
String[] cmd = { "/bin/sh", "-c", "grep 'Report Process started' server.log|wc -l" };
Process proc = rt.exec(cmd);
BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
System.out.println("Done");
}
You don't need to pipe grep's output to wc -l. Just use grep -c like this:
String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"};
Though I must say that doing this right inside Java is much cleaner. Consider code like this:
String logdata = new Scanner(new File("/path/to/server.log")).useDelimiter("\\Z").next();
final String needle = "Report Process started";
int occurrences = 0;
int index = 0;
while (index < logdata.length() && (index = logdata.indexOf(needle, index)) >= 0) {
occurrences++;
index += needle.length();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With