Created
January 2, 2018 22:19
-
-
Save mdnmdn/a062e7c5e28d78c5915ed1d0b292f534 to your computer and use it in GitHub Desktop.
node bulk rename with regex replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs_orig = require('fs'); | |
const util = require('util'); | |
const fs = { | |
readdir: util.promisify(fs_orig.readdir), | |
rename: util.promisify(fs_orig.rename), | |
} | |
const l = console.log.bind(console); | |
const rules = [ | |
{ | |
file_search: /.*(Masha e Orso)\s-\s(.*)S(\d\d)E(\d\d).*/, | |
rename: 'MO-$3x$4-$1-$2.mp4', | |
replace_white_spaces: '.', | |
}, | |
{ | |
file_search: /.*(PJ Masks)\s-\s(.*)S(\d\d)E(\d\d).*/, | |
rename: 'PJ-$3x$4-$1-$2.mp4', | |
replace_white_spaces: '.', | |
}, | |
{ | |
file_search: /.*(YO YO)\s-\s(.*)S(\d\d)E(\d\d).*/, | |
rename: 'YO-$3x$4-$1-$2.mp4', | |
replace_white_spaces: '.', | |
}, | |
{ | |
file_search: /.*(PJ Masks).*(\d\dx\d\d)\s-\s(.*)by\sSuper.*/, | |
rename: 'PJ-$2-$1-$3.mp4', | |
replace_white_spaces: '.', | |
}, | |
{ | |
file_search: /¡/g, | |
rename: '', | |
}, | |
]; | |
(async () => { | |
try{ | |
const r = await fs.readdir('.'); | |
const files = r.map(f => ({ orig: f, dest: f, changed: false})); | |
rules.forEach(ren => { | |
files.forEach(f => { | |
if (ren.file_search.test(f.dest)){ | |
f.changed = true; | |
f.dest = f.dest.replace(ren.file_search, ren.rename); | |
if (ren.replace_white_spaces){ | |
f.dest = f.dest.replace(/\s/g,ren.replace_white_spaces); | |
} | |
} | |
}); | |
}); | |
for(const idx in files){ | |
const f = files[idx]; | |
if (f.changed) | |
await fs.rename(f.orig, f.dest); | |
l(f.dest); | |
} | |
} catch(error) { | |
l(error); | |
} | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment