Skip to content

Instantly share code, notes, and snippets.

@sensboston
Last active October 6, 2021 04:24
Show Gist options
  • Save sensboston/ce4251c16cf83b82f64423bdd8a00e96 to your computer and use it in GitHub Desktop.
Save sensboston/ce4251c16cf83b82f64423bdd8a00e96 to your computer and use it in GitHub Desktop.
Tiny program for quick words replacement in UTF8 text files
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace find_rep
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (!File.Exists("find_rep.cfg"))
{
Console.WriteLine("Configuration file find_rep.cfg is missing: nothing to find");
}
else if (args.Length == 0 || !File.Exists(args[0]))
{
Console.WriteLine("No input file provided. Usage find_rep.exe <text_file>");
}
else
{
try
{
// Load dictionary
foreach (var s in File.ReadAllLines("find_rep.cfg"))
{
var kv = s.Split(new char[] { '\t' });
if (kv.Length == 2) dict[kv[0]] = kv[1];
}
// Do all replacements
var text = File.ReadAllText(args[0]);
foreach (var kv in dict)
text = ReplaceWholeWord(text, kv.Key, kv.Value);
// Save file
File.WriteAllText(args[0], text);
}
catch (Exception e)
{
Console.WriteLine("Exception during execution: " + e.Message);
}
}
}
static string ReplaceWholeWord(string original, string wordToFind, string replacement)
{
string pattern = string.Format(@"\b{0}\b", wordToFind);
return Regex.Replace(original, pattern, replacement, RegexOptions.None);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment