import java.io.*; /** * Searches the input file (or standard input if no file is given) * for lines containing the given pattern and prints these lines. *

* Usage: java Grep PATTERN [FILE] * * @author Stefan Nilsson * @version 2006.02.23 */ public class Grep { private static final String NAME = "Grep"; private static final String USAGE = "Usage: java " + NAME + " PATTERN [FILE]"; private static final String STDIN = "stdin"; private static final String OPEN_ERR = NAME + ": cannot open "; private static final String READ_ERR = NAME + ": error reading "; private Grep() {} /** * Searches the input file (argv[1] or standard input if no file * is given) for lines containing the given pattern (argv[0]) and * prints these lines. */ public static void main(String[] args) { if (args.length == 0 || args.length > 2) { System.err.println(USAGE); System.exit(1); } final String PATTERN = args[0]; final String FILE_NAME = args.length == 1 ? STDIN : args[1]; BufferedReader in = null; try { if (args.length == 1) in = new BufferedReader(new InputStreamReader(System.in)); else in = new BufferedReader(new FileReader(FILE_NAME)); (new Grep()).search(PATTERN, in); } catch (FileNotFoundException e) { System.err.println(OPEN_ERR + FILE_NAME); } catch (IOException e) { System.err.println(READ_ERR + FILE_NAME); } finally { try { if (in != null) in.close(); } catch (IOException e) { // At least we tried. } } System.exit(0); } /** * Prints all lines in the stream that contain the pattern. */ private void search(String pattern, BufferedReader in) throws IOException { String line; while ((line = in.readLine()) != null) if (line.indexOf(pattern) != -1) System.out.println(line); } }