Implement an Unix grep in Java
28/01/2009
import org.apache.regexp.*; import java.util.*; import java.io.*; /** * So as to test it run %JAVA_HOME%\bin\java -classpath .;jakarta-regexp.jar StringTool 2 */ public class grep { public static String[] split(String source, String regexp) { RE re = new RE(regexp); return re.split(source); } public static String[] grep(Object[] sources, String regexp) { RE re = new RE(regexp); return re.grep(sources); } public static boolean match(String source, String regexp) { RE re = new RE(regexp); return re.match(source); } public static void main(String[] argv) { try { if(argv.length == 2) { //File f = new File(argv[1]); //FileReader r = new FileReader(new File(argv[1])); FileReader in = new FileReader(new File(argv[1])); BufferedReader r = new BufferedReader(in); String line = r.readLine(); while(line != null) { if(match(line, argv[0])) System.out.println(line); line = r.readLine(); } r.close(); } else { System.out.println("Usage: grep regexp file"); } } catch(Exception e) { e.printStackTrace(); } } }