Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Grep command from java

Tags:

java

grep

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");
}
like image 892
Ramu Pasupuleti Avatar asked Aug 04 '26 16:08

Ramu Pasupuleti


1 Answers

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();
}
like image 195
anubhava Avatar answered Aug 07 '26 05:08

anubhava