Skip to content

Instantly share code, notes, and snippets.

@goodwin64
Last active November 21, 2021 15:46
Show Gist options
  • Save goodwin64/b142d90d33e36fbd93871e31c094ca3a to your computer and use it in GitHub Desktop.
Save goodwin64/b142d90d33e36fbd93871e31c094ca3a to your computer and use it in GitHub Desktop.
File counter rename script (0 external dependencies)
// only built-in Node.js dependencies
const fs = require('fs')
const path = require('path')
const util = require('util')
// working dir
const dir = 'C:\\Users\\werey\\Documents\\Scanned Documents'
// difference between file name counter and page number on image
const offset = 5
// temporary suffix (used only while program runs)
const TEMP_SUFFIX = 'TEMP_SUFFIX'
const rename = util.promisify(fs.rename);
async function main() {
// 1st loop - prepare for renaming: rename + add temp suffix (not to override files with names collision)
let files = fs.readdirSync(dir)
for (const file of files) {
// skip nested directories + misc files
if (!file.startsWith('Image')) {
continue;
}
const oldPath = path.resolve(dir, file)
console.log('old path ', oldPath)
const newName = file.replace(/(\d+)/g, (match, counter) => Number(counter) + offset).concat(TEMP_SUFFIX)
const newPath = path.resolve(dir, newName)
console.log('temp path 1', newPath)
console.log('\n')
await rename(oldPath, newPath);
}
// 2nd loop - final renaming: remove temp suffix
files = fs.readdirSync(dir)
for (const file of files) {
if (!file.startsWith('Image')) {
continue;
}
const oldPath = path.resolve(dir, file)
console.log('temp path 2', oldPath)
const newName = file.replace(TEMP_SUFFIX, '')
const newPath = path.resolve(dir, newName)
console.log('new path ', newPath)
console.log('\n')
await rename(oldPath, newPath);
}
}
main();
@goodwin64
Copy link
Author

Result

Result

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