Skip to content

Instantly share code, notes, and snippets.

@scriptex
Last active April 10, 2023 23:30
Show Gist options
  • Save scriptex/20536d8cda36221f91d69a6bd4a528b3 to your computer and use it in GitHub Desktop.
Save scriptex/20536d8cda36221f91d69a6bd4a528b3 to your computer and use it in GitHub Desktop.
Rename all files in a folder with NodeJS
const { join } = require('path');
const { readdirSync, renameSync } = require('fs');
const [dir, search, replace] = process.argv.slice(2);
const match = RegExp(search, 'g');
const files = readdirSync(dir);
files
.filter(file => file.match(match))
.forEach(file => {
const filePath = join(dir, file);
const newFilePath = join(dir, file.replace(match, replace));
renameSync(filePath, newFilePath);
});
// Usage
// node rename.js path/to/directory 'string-to-search' 'string-to-replace'
@ramboi234
Copy link

how to fix space on path?
E:\MEMEK\sound effect\

@scriptex
Copy link
Author

scriptex commented Jan 14, 2021

@ultrasamad @ramboi234
If you have spaces in the filenames make sure that your strings to search and replace are wrapped in 's (or "s).

Example:

node rename.js ./folder/ 'file-name with-spaces' 'file-name-without-spaces'

If you have spaces in your folder name, then you need to escape the spaces. On UNIX based systems (such as MacOS and Linux) you can escape by adding a \ in front of the space. Like this:

node rename.js ./folder\ with\ spaces\ in\ the\ name/ 'file-name with-spaces' 'file-name-without-spaces' 

The examples above are with a folder structure like this:

πŸ“¦ project
β”— πŸ“œ rename.js    
┣ πŸ“‚ folder with spaces in the name
┃ β”— πŸ“œ file-name-without-spaces copy 2.txt
┃ β”— πŸ“œ file-name-without-spaces copy 3.txt
┃ β”— πŸ“œ file-name-without-spaces copy 4.txt
┃ β”— πŸ“œ file-name-without-spaces copy 5.txt
┃ β”— πŸ“œ file-name-without-spaces copy 6.txt
┃ β”— πŸ“œ file-name-without-spaces copy 7.txt
┃ β”— πŸ“œ file-name-without-spaces copy 8.txt
┃ β”— πŸ“œ file-name-without-spaces copy 9.txt
┃ β”— πŸ“œ file-name-without-spaces copy 10.txt
┃ β”— πŸ“œ file-name-without-spaces copy 11.txt
┃ β”— πŸ“œ file-name-without-spaces copy 12.txt
┃ β”— πŸ“œ file-name-without-spaces.txt

@Amjad-ND
Copy link

Amjad-ND commented Mar 3, 2021

I would ask about pdf file !

I have a pdf file and I would to generate QR code when rename file. ex: file name is 12345678 the QR code must represent this value .
note : programing language that used in adobe acrobat pro dc is JavaScript

@Amjad-ND
Copy link

Amjad-ND commented Mar 3, 2021

InkedSharedScreenshot_LI

@scriptex
Copy link
Author

@Amjad-ND what you're asking has nothing to do with the code shown in this gist.
I would suggest going to Stackoverflow or any similar website and try to find some resources/ideas which will help you accomplish your task.

@ShahriarKh
Copy link

Thank you man

@jonasfrey
Copy link

perfect

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