Today, the project encountered a requirement to batch rename all files in a directory, and found that everyone handled it in a completely different way:

General engineer

Rename files in batches on Mac is very convenient, as long as you batch select all files, right click “rename” will pop up an input box, select matching rules, and then enter the replacement text, for example, 1. Jpeg ~ 3. Jpeg suffixes change to.png, you can operate like this:

So what if you want to recursively change all files in a directory with a given suffix? For example, changing all.ts files in the SRC directory to.js won’t work.

Senior Engineer

Rename will be installed with one line of code:

brew install rename
find . -type f -name "*.ts" -print | xargs rename 's/\.ts/\.js/'
Copy the code

You can add the -n parameter if you just want to see the substitution effect, but do not actually replace it, for example:

$ find . -type f -name "*.ts" -print | xargs rename -n 's/\.ts/\.js/'
'./order.class.ts' would be renamed to './order.class.js'
'./order.service.ts' would be renamed to './order.service.js'
'./order.hooks.ts' would be renamed to './order.hooks.js'
Copy the code

Senior Engineer

If there are more complex rules, you can only write scripts in any language such as NodeJS, Python, Java, Go, etc. For example, write a rename function with node.js to rename all files or folders under the specified folder with a prefix as follows:

const fs = require("fs")
const path = require('path')

function rename(dir, prefix = 'rename_') {
  fs.readdir(dir, (e, files) = > {
    for (let i = 0; i < files.length; i++) {
      let f = files[i]
      fs.rename(path.join(dir, f), path.join(dir, prefix + f), (err) = > {
        if (err) throw err
        console.log(f + '- >' + prefix + f)
      })
    }
  })
}
rename(__dirname)
Copy the code

For example, if you want to find all js and JSX files in the SRC directory, you need to use the glob syntax:

const glob = require('glob')
const files = glob.sync('src/**/*.js{,x}')
console.log(files)
Copy the code

Now that you have the absolute path to the file, it’s easy to just call the fs.rename method and replace it with the name you want. Git will be able to find and roll back errors if they occur:

git checkout . && git clean -xdf
Copy the code