Skip to content

Instantly share code, notes, and snippets.

@chaojian-zhang
Created March 21, 2021 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaojian-zhang/221c2982b3b4f4cf94911274ed3f9faa to your computer and use it in GitHub Desktop.
Save chaojian-zhang/221c2982b3b4f4cf94911274ed3f9faa to your computer and use it in GitHub Desktop.
A CLI (Command Line Interface) utility to rename files with regular expression (C# style). Itch.IO: https://charles-zhang.itch.io/rename
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace RegRename
{
class Program
{
static void Main(string[] args)
{
if(args.Length == 0)
{
Console.WriteLine(
@"Regular Expression Rename Utility: Rename all files inside a folder with a given (C# regular expression) pattern.
Arguments format: FolderPath SourcePattern ReplacementPattern (NoAsk)
FolderPath: Source folder containing files to replace.
SourcePattern: Source file pattern.
ReplacementPattern: Replacement pattern.
NoAsk: Specify ""NoAsk"" (case-sensitive) to skip confirmation."
);
}
else
{
// Argument check
if (args.Length < 3)
{
Console.WriteLine("Insufficient number of arguments.");
return;
}
// Confirmation toggle
bool askForConfirmation = true;
if (args.Length == 4 && args[3] == "NoAsk")
askForConfirmation = false;
// Extract parameters
string sourceFolder = args[0];
string sourcePattern = args[1];
string targetPattern = args[2];
// Path validation
if(!Directory.Exists(sourceFolder))
{
Console.WriteLine($"Source folder `{sourceFolder}` doesn't exist.");
return;
}
// File selection
var files = Directory.GetFiles(sourceFolder).Where(f => Regex.IsMatch(f, sourcePattern));
var replacements = files.Select(f => (OriginalPath: f, NewPath: Regex.Replace(f, sourcePattern, targetPattern))).ToList();
// Path confirmation
foreach (var rule in replacements)
{
Console.WriteLine($"Replace `{Path.GetFileName(rule.OriginalPath)}` with `{Path.GetFileName(rule.NewPath)}`");
}
Console.WriteLine($"Found {replacements.Count} files matching replacement pattern.");
Console.Write("Confirm replacement? [Y/N] ");
string reply = Console.ReadLine();
if(GetConfirmation(reply.ToLower()) == true)
{
try
{
foreach (var rule in replacements)
{
File.Move(rule.OriginalPath, rule.NewPath);
}
Console.WriteLine($"Replaced {replacements.Count} files.");
}
catch (Exception e)
{
Console.WriteLine($"An error is encountered when trying to replace file: {e.Message}");
Console.WriteLine(e.StackTrace);
return;
}
}
else
{
Console.WriteLine("Replacement aborted.");
return;
}
}
}
private static bool GetConfirmation(string reply)
{
switch (reply)
{
case "y":
case "yes":
case "ok":
return true;
default:
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment