001package org.unix4j.unix.grep; 002 003import org.unix4j.context.ExecutionContext; 004import org.unix4j.line.Line; 005import org.unix4j.line.SimpleLine; 006import org.unix4j.processor.LineProcessor; 007import org.unix4j.util.Counter; 008 009/** 010 * Writes the matching line count to the output. The matching operation is delegated 011 * to the {@link LineMatcher} passed to the constructor. 012 */ 013final class CountMatchingLinesProcessor extends AbstractGrepProcessor { 014 015 private final Counter counter = new Counter(); 016 017 public CountMatchingLinesProcessor(GrepCommand command, ExecutionContext context, LineProcessor output, LineMatcher matcher) { 018 super(command, context, output, matcher); 019 } 020 021 @Override 022 protected boolean processLine(Line line, boolean isMatch) { 023 if (isMatch) { 024 counter.increment(); 025 } 026 return true;//even if line is not a match, we still want the next line 027 } 028 029 @Override 030 public void finish() { 031 try { 032 getOutput().processLine(new SimpleLine(String.valueOf(counter.getCount()))); 033 super.finish(); 034 } finally { 035 counter.reset(); 036 } 037 } 038}