请确保已删除重复的文件
以下是使用 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
函数进行重命名,并在控制台输出相应的操作信息。
请注意,在运行此代码之前,请确保在运行目录下存在文件,因为它仅会在当前目录及其子目录中搜索文件并进行处理。