Skip to content

Instantly share code, notes, and snippets.

@yoeran
Created August 1, 2017 10:31
Show Gist options
  • Save yoeran/2db558a4da5ecf59d25cff1c3a8d069e to your computer and use it in GitHub Desktop.
Save yoeran/2db558a4da5ecf59d25cff1c3a8d069e to your computer and use it in GitHub Desktop.
Simple NodeJS script for batch renaming files using Regex
/**
* Usage:
* node renamer.js [files] "[regexMatcher]" "[regexReplace]"
*
* Example:
* node rename.js *.mp3 "(.*)-([0-9].*)\.mp3" "%1.mp3"
*
* Extra tip: Add an alias to your .bash_profile that allows you to use `rename` anywhere.
* alias rename="node PATH_TO_SCRIPT/renamer.js"
*/
console.log("\n-- Let's rename some stuff! --");
const fs = require("fs");
const readline = require("readline");
// SETUP VARS
const files = process.argv.slice(2, -2);
const regexMatch = new RegExp(process.argv.slice(-2).shift());
const regexReplace = process.argv.slice(-1).shift().replace(/%/, "$");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const renameLog = [];
console.log("\n\n-- Rename example --");
files.forEach(current => {
let newName = current.replace(regexMatch, regexReplace);
console.log(`${current}\t\t->\t${newName}`);
renameLog.push({current, newName});
});
rl.question("\n\n-- Want to rename the files like above? (y/n) ", function (answer) {
if (answer === "y") {
console.log("Renaming...");
while (renameLog.length) {
const change = renameLog.pop();
fs.rename(change.current, change.newName, (err) => {
if (err) { console.log("ERROR:", err); }
if (renameLog.length === 0) {
console.log("Done! Bye!");
process.exit();
}
});
}
} else {
console.log("Too bad...");
process.exit();
}
});
@yoeran
Copy link
Author

yoeran commented Aug 1, 2017

I found myself manually renaming a lot of files every once in a while and never found a tool that did the trick for me. I thought: "If I could just write some regex to do this simple stuff". So I made this script.

The example in the comment was used to strip of some numbers off some mp3 filenames. They we're named like track-1234678.mp3 and wanted to have them like track.mp3.

Let me you if this is any use to you!

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