Skip to content

Instantly share code, notes, and snippets.

@librz
Last active September 8, 2023 20:19
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 librz/61156e472cc83fcb94ab8c99f874bcae to your computer and use it in GitHub Desktop.
Save librz/61156e472cc83fcb94ab8c99f874bcae to your computer and use it in GitHub Desktop.
Batch rename files (using regex with capture group)
// this script does not handle file suffix for you
// as some files have multiple suffix segments, e.g: *.sc.ass & *.tc.ass are two common subtitle formats
// instead, you should manually specify suffix in regex as the last capture group
const fs = require("fs")
const isDryrun = !process.argv.includes("-r");
if (isDryrun) {
console.log("Note: By default, this script will only dry run, specify -r if you want to actually run it.")
}
function getNewFilename(filename, regex, replaceWith) {
if (!filename || !filename.match(regex)) {
return filename
}
return filename.replace(re, replaceWith);
}
// rename file names in the current directory (using regex capture group)
function renameFiles(regex, replaceWith) {
const files = fs.readdirSync(__dirname).filter(filename => filename.match(re))
console.log(`${files.length} files matched`)
files.forEach(file => {
const newFile = getNewFilename(file, regex, replaceWith)
if (isDryrun) {
console.log(file, "->", newFile)
} else {
fs.rename(file, newFile, () => {
console.log(`${file} -> ${newFile}`)
})
}
})
}
/*
suppose under current folder, files are like:
[BeanSub&FZSD&VCB-Studio] Kimetsu no Yaiba [01][Ma10p_1080p][x265_flac_aac].mkv
[BeanSub&FZSD&VCB-Studio] Kimetsu no Yaiba [02][Ma10p_1080p][x265_flac_aac].mkv
[BeanSub&FZSD&VCB-Studio] Kimetsu no Yaiba [03][Ma10p_1080p][x265_flac_aac].mkv
and you want to rename them into:
EP01.mkv
EP02.mkv
EP03.mkv
then you can do:
const re = /^\[BeanSub.*Kimetsu no Yaiba \[([0-9][0-9])\].*(\.mkv)$/;
renameFiles(re, "EP$1$2") // $n means the nth capture group in regex
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment