Home   Cover Cover Cover Cover
  Replace.cs
// Replace  Replaces a pattern with a specified value in several files
// -------
// Syntax: replace pattern value filename {filename}
//
// The pattern is specified with a regular expression as it
// is common under .NET. If the value contains blanks it can be
// set under quotes ("..."). The filenames can contain the wildcard
// characters * and ?
// H.Moessenboeck, University of Linz, October 2002
//-------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;

class Replace {
  
  static ArrayList FileNames(string[] arg) {
    char[] wildCards = {'*', '?'};
    ArrayList list = new ArrayList();
    for (int i = 2; 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 Repl(Regex re, string value, string fn) {
    try {
      TextReader r = File.OpenText(fn);
      string text = r.ReadToEnd();
      Match match = re.Match(text);
      if (match.Success) {
        StringBuilder buf = new StringBuilder(text);
        do {
          buf.Remove(match.Index, match.Length);
          buf.Insert(match.Index, value);
          match = match.NextMatch();
        } while (match.Success);
        r.Close();
        TextWriter w = File.CreateText(fn);
        w.Write(buf.ToString());
        w.Close();
      }
    } catch (FileNotFoundException) {
      Console.WriteLine("-- file " + fn + " not found");
    }
  }
  
  static void Main(string[] arg) {
    if (arg.Length < 3) {
      Console.WriteLine("Syntax: Replace pattern value filename {filename}");
      return;
    }
    Regex re = new Regex(arg[0], RegexOptions.RightToLeft);
    string value = arg[1];
    if (value[0] == '"' && value[value.Length-1] == '"')
      value = value.Substring(1, value.Length-2);
    ArrayList files = FileNames(arg);
    foreach (string fn in files) Repl(re, value, fn);
  }
}