Hi folks,
Here's a tricky one (I think):
I need to search for words within a file. To do this, I thought of
using grep and executing from Runtime.getRuntime() instead of writing
something in Java.
Now, when I run the following in linux:
grep -c -x -F 'HOT' filetosearch.txt
The program prints out 1 which is correct as the file specified above
has just one occurrence of the word HOT on a single line. However, when
I put the same thing within Java like this:
Runtime rt = Runtime.getRuntime();
Process pt = rt.exec("grep -c -x -F 'HOT' filetosearch.txt");
Then the Java application always gets a 0 count.
Any ideas why? Also, is there any better way to do searching of text
files within java?
Gordon Beaton - 14 Aug 2006 20:49 GMT
> Runtime rt = Runtime.getRuntime();
> Process pt = rt.exec("grep -c -x -F 'HOT' filetosearch.txt");
[quoted text clipped - 3 lines]
> Any ideas why? Also, is there any better way to do searching of text
> files within java?
When you run the command from a shell, it removes the single quotes
from the search string and they aren't ever seen by grep.
When you run the command from Java, there is no shell and grep is
looking for the 5-characters 'HOT' (i.e. including the 2 single
quotes), which presumably isn't in your file.
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
rajatag - 15 Aug 2006 13:57 GMT
Thanks! I removed the quotes and it started to work fine!