Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Suppose you have many folders named with a number prefix:
1-yo
2-hey
3-cool
4-hi
5-whatsup
You need to insert a new folder in the middle and renumber the rest:
1-yo
2-hey
3-NEWONE
3-cool
4-hi
5-whatsup
You want to increment the numbers of all folders that come after the new one:
1-yo
2-hey
3-NEWONE
4-cool
5-hi
6-whatsup
You can automate this with a Node.js script. For example, save the script as increment.js and pass the starting number as a command-line argument:
node increment.js 4
Read the number from process.argv:
const args = process.argv.slice(2)
const startingNumber = args[0]
If no number is provided, show an error and exit:
if (!startingNumber) {
console.log('Add a number argument')
return
}
Run the script from the folder that contains the numbered subfolders. List the contents of the current folder:
const fs = require('fs')
const folders = fs
.readdirSync('./')
.map(fileName => {
return fileName
})
Filter to keep only folders:
const fs = require('fs')
const isFolder = fileName => {
return !fs.lstatSync(fileName).isFile()
}
const folders = fs
.readdirSync('./')
.map(fileName => {
return fileName
})
.filter(isFolder)
Iterate over the folders:
folders.map(folder => {
})
Extract the number from each folder name:
folders.map(folder => {
const result = folder.match(/(\d)+/)
})
If the name contains a number, parse it:
folders.map(folder => {
const result = folder.match(/(\d)+/)
if (result !== null) {
const num = parseInt(result[0])
}
})
If the folder number is greater than or equal to the starting number, rename it with the incremented number:
folders.map(folder => {
const result = folder.match(/(\d)+/)
if (result !== null) {
const num = parseInt(result[0])
if (num >= startingNumber) {
fs.renameSync(folder, folder.split(num).join(num + 1))
}
}
})
Full script:
const fs = require('fs')
const args = process.argv.slice(2)
const startingNumber = args[0]
if (!startingNumber) {
console.log('Add a number argument')
return
}
const isFolder = fileName => {
return !fs.lstatSync(fileName).isFile()
}
const folders = fs
.readdirSync('./')
.map(fileName => {
return fileName
})
.filter(isFolder)
folders.map(folder => {
const result = folder.match(/(\d)+/)
if (result !== null) {
const num = parseInt(result[0])
if (num >= startingNumber) {
fs.renameSync(folder, folder.split(num).join(num + 1))
}
}
})