0

SOLVED SEE COMMENT BELOW

Ok, this one is tricky:

I call this command from Java with Process.exec():

grep -ne 'xxx\|yyy' file

and it only returns xxx?

Edit: I escape the \ with \\ in java.

But when I call the exact same command from the commandline on the same machine it returns both xxx and yyy as expected!?

I have tried everything, escaping more and less with -E, changing ' to " (which actually oddly doesn't work when you run from java either)?!

Has someone run in to the exact same odd problem?

4
  • 1
    Can you try this command: grep -ne 'xxx\\|yyy' file OR grep -n -e 'xxx' -e 'yyy' file ? Commented Mar 20, 2013 at 19:50
  • Of course I escape the \ in the java code with \\ othervise this wouldn't work at all. Commented Mar 20, 2013 at 19:59
  • If the | has to be escaped on the command line, you might have to use 3 or 4 \ characters in your Java string! Commented Mar 20, 2013 at 20:06
  • ok SOLVED thanks to anubhava... grep -n -e 'xxx' -e 'yyy' file didnt work but then I tried grep -n -e 'xxx' file and that didnt work either so I tried grep -ne 'xxx\|yyy\|zzz' file and THEN xxx and yyy returned lol Commented Mar 20, 2013 at 20:14

2 Answers 2

1

You will have to escape '\' by putting '\\' as follows :

.exec("grep -ne 'xxx\\|yyy' file");
Sign up to request clarification or add additional context in comments.

Comments

1

This might be a dumb question, but why not use BufferedReader/readLine, and then String.indexOf or other regex, rather than shelling out to grep?

Grep is probably faster than Java at searching the file, but on the other hand, creating a child process from Java would probably negate any benefit gained there.

1 Comment

Because xxx and yyy are complex and need regexp anyhow + the file is BIG!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.