Java Grep

November 9, 2007

Submitted by: Taoufix

Category: Computers

152 views

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileReader;
import java.io.FileNotFoundException;
 
public class Grep {
  public static void error(String msg) {
    System.err.println(msg);
    System.exit(1);
  } 
 
  public static void main(String[] args) {
    BufferedReader input;
    Matcher matcher;
    Pattern pattern;
    String line;
 
    switch (args.length) {
    case 1:
      input =  new BufferedReader(new InputStreamReader(System.in));
      break;
    case 2:
      try {
        input =  new BufferedReader(new FileReader(args[1]));
      } catch (FileNotFoundException e) {
        input = null; // silly java
        error("Error: " + args[1] + ": " + e.getMessage());
      }
      break;
    default:
      input = null; // silly java
      error("Usage: java Grep PATTERN [file]");
    }
 
    pattern = Pattern.compile(".*" + args[0] + ".*");
 
    try {
      while ((line = input.readLine()) != null) {
        matcher = pattern.matcher(line);
        if (matcher.matches()) {
          System.out.println(line);
        }
      }
    } catch (IOException e) {
      error("Error parsing input: " + e.getMessage());
    }
  }
}
If you liked this, please share it at your favorite sites:
  • Digg
  • Reddit
  • del.icio.us
  • Wikio
  • Facebook
  • Google
  • Technorati
  • TwitThis
  • MySpace
  • N4G
  • NewsVine
  • StumbleUpon
  • BlogMemes
  • Blogsvine
  • blogtercimlap
  • description
  • eKudos
  • Faves
  • Fleck
  • Scoopeo
  • Socialogs
  • Upnews
  • Yigg
  • E-mail this story to a friend!
  • Mixx

Leave a Reply

:D :) :cry: :( 8O :twisted: :!: :vangry: :XO: :up: ;) :mrgreen: :halo: :kiss: :roll: :? 8) :evil: :oops: :| :?: :x :$: more »