package pbt.iotest;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/** 
 * Grep, permet de rechercher les lignes d'un fichier correspondant à 
 * un certain motif. 
 * 
 * Ceci est une version simplifiée de la commande unix grep pour un seul fichier et 
 * un motif simple. 
 * 
 * @author pbt
 */
public class Grep {

	
	public static void main(String[] args) {
		final String USAGE = "Usage: java pbt.iotest.Grep <motif> <file>" ;
		BufferedReader reader ; 
		String motif ;
		String ligne ; 
		
		if ( args.length != 2 ) {
			System.out.println(USAGE); 
			System.exit(1) ; 
		}
		// À ce stade, je sais que le nombre de paramètres est correct.
		motif = args[0] ; 
		try {
			reader = new BufferedReader( 
					new FileReader( args[1] ) ) ;
			while ( (ligne=reader.readLine()) != null ) {
				if ( ligne.matches(".*" + motif + ".*") ) {
					System.out.println(ligne);
				}
			}
			reader.close() ; 
		} catch ( FileNotFoundException fnfe ) {
			System.err.println("File not found");
			System.exit(1) ; 
		} catch ( IOException ioe ) {
			System.err.println("Erreur d'E/S");
			System.exit(1) ; 
		}
	}
}
