批量删除文件重复的(1)后缀

请确保已删除重复的文件

以下是使用 JavaScript 编写的代码,用于检索当前目录及其子目录下的所有文件,并删除文件名中的"(1)":

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

function findFiles(dirPath, fileList = []) {
  const files = fs.readdirSync(dirPath);

  files.forEach((file) => {
    const filePath = path.join(dirPath, file);
    const stats = fs.statSync(filePath);

    if (stats.isDirectory()) {
      findFiles(filePath, fileList);
    } else if (stats.isFile()) {
      fileList.push(filePath);
    }
  });

  return fileList;
}

function removeDuplicateNumberFromFileName(filePath) {
  const fileName = path.basename(filePath);
  const regex = /\(\d+\)/g;
  const newFileName = fileName.replace(regex, '');
  const newPath = path.join(path.dirname(filePath), newFileName);

  fs.renameSync(filePath, newPath);
}

const currentDir = process.cwd();
const fileList = findFiles(currentDir);

fileList.forEach((filePath) => {
  const fileName = path.basename(filePath);
  if (/\(\d+\)/.test(fileName)) {
    removeDuplicateNumberFromFileName(filePath);
    console.log(`Removed "(1)" from file name: ${fileName}`);
  }
});

这段代码首先使用fs模块和path模块来处理文件和路径。findFiles函数递归地搜索当前目录及其子目录下的所有文件,并将它们存储在一个文件列表中。然后,removeDuplicateNumberFromFileName函数接收文件路径作为参数,从文件名中删除"(1)",并使用fs.renameSync重命名文件。

最后,代码会遍历文件列表,对于文件名中带有"(1)"的文件,调用removeDuplicateNumberFromFileName函数进行重命名,并在控制台输出相应的操作信息。

请注意,在运行此代码之前,请确保在运行目录下存在文件,因为它仅会在当前目录及其子目录中搜索文件并进行处理。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容