Home   Cover Cover Cover Cover
  Grep.cs
// Grep  Regular expression search in several files
// ----
// Syntax: grep pattern filename {filename}
//
// The pattern is specified with a regular expression as it
// is common under .NET. The filenames can contain the wildcard
// characters * and ?
// H.Moessenboeck, University of Linz, October 2002
//-------------------------------------------------------------------
using System;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

class Grep {
  
  static ArrayList FileNames(string[] arg) {
    char[] wildCards = {'*', '?'};
    ArrayList list = new ArrayList();
    for (int i = 1; i < arg.Length; i++) {
      if (arg[i].IndexOfAny(wildCards) >= 0) {
        string dir;
        string path = arg[i];
        int pos = path.LastIndexOf('\\');
        if (pos >= 0) {
          dir = path.Substring(0, pos+1); path = path.Substring(pos+1);
        } else
          dir = Directory.GetCurrentDirectory();
        string[] files = Directory.GetFiles(dir, path);
        foreach (string s in files) list.Add(s);
      } else list.Add(arg[i]);
    }
    return list;
  }
    
  static void PrintLine(string text, int pos) {
    int beg = pos;
    while (beg >= 0 && text[beg] != '\n') beg--;
    int end = pos;
    while (end < text.Length && text[end] != '\r') end++;
    Console.WriteLine(text.Substring(beg+1, end-beg-1));
  }
  
  static void Find(Regex re, string fn) {
    try {
      TextReader r = File.OpenText(fn);
      string text = r.ReadToEnd();
      Match match = re.Match(text);
      if (match.Success) {
        Console.WriteLine("-- " + fn);
        do {
          PrintLine(text, match.Index);
          match = match.NextMatch();
        } while (match.Success);
        Console.WriteLine();
      }
    } catch (FileNotFoundException) {
      Console.WriteLine("-- file " + fn + " not found");
    }
  }
  
  static void Main(string[] arg) {
    if (arg.Length < 2) {
      Console.WriteLine("Syntax: Grep pattern filename {filename}");
      return;
    }
    Regex re = new Regex(arg[0]);
    ArrayList files = FileNames(arg);
    foreach (string fn in files) Find(re, fn);
  }
}