-2

I want to execute the following command through Java code. Can any one suggest how can I execute it?

find ./path/ | grep "keyword" | grep -rnw -e "keyword"

I am trying in many way, but not getting proper output.

  • 1
    We can't see your code so we can't tell you what's wrong with it. It should not be hard to find examples of this on the net. – tripleee Nov 27 '17 at 09:26
  • Guys you say it's a duplicate of other question but you specify just one duplicate, it's actually a combination of few other questions I would say. Especially that original question marked here doesn't talk about pipes at all ... You're a bit too quick to mark as duplicate in my opinion – Grzegorz Gralak Nov 27 '17 at 10:07

1 Answers1

0

Runtime.getRuntime().exec() is your friend here.

Guys are right that it is a duplication of few other questions but mostly this one: How to make pipes work with Runtime.exec()?

Printing out the response is covered better here: java runtime.getruntime() getting output from executing a command line program

It seems like you want to execute pipes through java code. I found using shell or bash the easiest. You could also explore org.apache.commons.exec package if you can.

Here is how I would do it:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String argv[]) {
        try {
            String[] cmd = {
                    "/bin/sh",
                    "-c",
                    "find ./path/ | grep \"keyword\" | grep -rnw -e \"keyword\""
            };

            Process exec = Runtime.getRuntime().exec(cmd);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));

            System.out.println("Standard output:\n");
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            System.out.println("Error output:\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Grzegorz Gralak
  • 717
  • 8
  • 7
  • Hello Gralak, Thanks for your valuable response!! I do have another doubt. I wanted to grep "somekey="value"" /path/fileName. From command window, I got the output by using / (grep "somekey=\"value\"" /path/fileName). But from Java, it is not working.. Do you have any solutions? – Preethi Hacker Nov 28 '17 at 17:34