Back to roadmaps regex Course

Project: Bulk File Rename with Date Format Normalization

In this project, we will write a Node.js script that scans a directory for files with inconsistent date formats in their names (like report_2026.06.16.pdf or report_16-06-2026.pdf) and renames them all to a consistent standard format (report_2026-06-16.pdf).


1. The Rename Script

Create bulk-rename.js:

// bulk-rename.js
const fs = require('fs');
const path = require('path');

const TARGET_DIR = './reports';

// Pattern 1: Matches "YYYY.MM.DD" format (e.g., 2026.06.16)
const FORMAT_DOTS = /^(?<prefix>.+?)_(?<year>\d{4})\.(?<month>\d{2})\.(?<day>\d{2})(?<ext>\.\w+)$/;

// Pattern 2: Matches "DD-MM-YYYY" format (e.g., 16-06-2026)
const FORMAT_DMY = /^(?<prefix>.+?)_(?<day>\d{2})-(?<month>\d{2})-(?<year>\d{4})(?<ext>\.\w+)$/;

function normalizeFilename(filename) {
  let match;

  // Try matching "YYYY.MM.DD" format first
  match = filename.match(FORMAT_DOTS);
  if (match) {
    const g = match.groups;
    return `${g.prefix}_${g.year}-${g.month}-${g.day}${g.ext}`;
  }

  // Try matching "DD-MM-YYYY" format
  match = filename.match(FORMAT_DMY);
  if (match) {
    const g = match.groups;
    return `${g.prefix}_${g.year}-${g.month}-${g.day}${g.ext}`;
  }

  return null; // No pattern matched; skip this file
}

function renameFiles(directory) {
  const files = fs.readdirSync(directory);
  let renamedCount = 0;

  for (const filename of files) {
    const newFilename = normalizeFilename(filename);
    
    if (newFilename && newFilename !== filename) {
      const oldPath = path.join(directory, filename);
      const newPath = path.join(directory, newFilename);
      
      fs.renameSync(oldPath, newPath);
      console.log(`Renamed: "${filename}" -> "${newFilename}"`);
      renamedCount++;
    }
  }

  console.log(`Done. Total files renamed: ${renamedCount}`);
}

renameFiles(TARGET_DIR);

2. Running the Script

Place files with inconsistent date formats in the ./reports/ folder:

report_2026.06.16.pdf
summary_16-06-2026.xlsx
invoice_2026.06.01.docx

Run the script:

node bulk-rename.js

Output:

Renamed: "report_2026.06.16.pdf" -> "report_2026-06-16.pdf"
Renamed: "summary_16-06-2026.xlsx" -> "summary_2026-06-16.xlsx"
Renamed: "invoice_2026.06.01.docx" -> "invoice_2026-06-01.docx"
Done. Total files renamed: 3
Published on Last updated: