从java运行Grep命令
我想从java运行grep命令 这是我试过的。请让我知道,为什么它不显示输出从java运行Grep命令,java,grep,Java,Grep,我想从java运行grep命令 这是我试过的。请让我知道,为什么它不显示输出 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.e
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");
}
您不需要将grep的输出传输到
wc-l
。只需像这样使用grep-c
:
String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"};
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();
}
尽管我必须说,在Java中正确地执行此操作要干净得多。考虑这样的代码:
String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"};
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();
}
String logdata=new Scanner(新文件(“/path/to/server.log”))。使用分隔符(\\Z”).next();
最终字符串needle=“报告过程已开始”;
int=0;
int指数=0;
而(索引=0){
事件++;
索引+=针的长度();
}
您必须检查是否有任何错误
private static void printStream(InputStream in) throws IOException {
BufferedReader is = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
}
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
String[] cmd = {"/bin/sh", "-c", "grep 'Report Process started' server.log|wc -l"};
Process proc = rt.exec(cmd);
printStream(proc.getInputStream());
System.out.println("Error : ");
printStream(proc.getErrorStream());
} catch (Exception ex) {
ex.printStackTrace();
}
}
你为什么要外包
grep
?@chrylis,我想在日志文件中获得“Report Process started”字符串的计数。。。有没有其他方法可以让我计算这个字符串的数量…suggestRight,那么为什么不自己用Java来计算呢?或者运行shell脚本中的所有内容?请尝试提供日志文件的完整路径。