Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created January 31, 2019 22:49
Show Gist options
  • Save scottoffen/1b3ad640fccc26f889caa5ec90dc9145 to your computer and use it in GitHub Desktop.
Save scottoffen/1b3ad640fccc26f889caa5ec90dc9145 to your computer and use it in GitHub Desktop.
Rename files downloaded from Packt via LinqPad
void Main()
{
var dir = @"Y:\Downloads\My Books\";
var filepaths = Directory.GetFiles(dir, "*.pdf", SearchOption.TopDirectoryOnly);
var pattern = @"^\d{13}\-(\w+)\.pdf$";
var regex = new Regex(pattern);
foreach (var filepath in filepaths)
{
var filename = Path.GetFileName(filepath);
if (!regex.IsMatch(filename)) continue;
var matches = regex.Matches(filename);
var fnbuilder = new StringBuilder();
foreach (var part in matches[0].Groups[1].Value.ToLower().Split('_'))
{
fnbuilder.Append(part.First().ToString().ToUpper() + part.Substring(1) + "_");
}
var newfilename = fnbuilder.ToString().TrimEnd('_') + ".pdf";
var newfilepath = Path.Combine(dir, newfilename);
if (File.Exists(newfilepath))
{
Console.WriteLine(newfilepath);
}
else
{
File.Move(filepath, newfilepath);
}
}
}
@scottoffen
Copy link
Author

Example

Renames 9781788628815-UNDERSTANDING_SOFTWARE.pdf to Understanding_Software.pdf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment