FileDocCategorySizeDatePackage
SimpleGrep.javaAPI DocExample1352Mon May 06 19:21:08 BST 2002com.ronsoft.books.nio.regex

SimpleGrep

public class SimpleGrep extends Object
Simple implementation of the ubiquitous grep command. First argument is the regular expression to search for (remember to quote and/or escape as appropriate). All following arguments are filenames to read and search for the regular expression. Created: April, 2002
author
Ron Hitchens (ron@ronsoft.com)
version
$Id: SimpleGrep.java,v 1.1 2002/05/07 02:21:08 ron Exp $

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] argv)

		if (argv.length < 2) {
			System.out.println ("Usage: regex file [ ... ]");
			return;
		}

		Pattern pattern = Pattern.compile (argv [0]);
		Matcher matcher = pattern.matcher ("");

		for (int i = 1; i < argv.length; i++) {
			String file = argv [i];
			BufferedReader br = null;
			String line;

			try {
				br = new BufferedReader (new FileReader (file));
			} catch (IOException e) {
				System.err.println ("Cannot read '" + file
					+ "': " + e.getMessage());
				continue;
			}

			while ((line = br.readLine()) != null) {
				matcher.reset (line);

				if (matcher.find()) {
					System.out.println (file + ": " + line);
				}
			}

			br.close();
		}