Batch File Rename: How to Rename Files Using a Batch Script

Abstract: Automate bulk file renaming across Windows, Linux, and macOS using batch scripts and shell commands to save time on large directories.

Created: 2026-08-02 by
Renaming multiple files simultaneously is a common task that can be automated using batch scripts on Windows or shell scripts on Linux and macOS. By leveraging simple command-line tools like ren for Windows or mv for Unix-like systems, you can efficiently update file names based on specific patterns without manual intervention. This approach saves significant time when dealing with large directories of similarly named assets.

Windows Batch Scripting Basics

On Windows, the built-in ren (or rename) command allows you to change file names within a single directory. While it does not support wildcards in the destination name directly for complex pattern replacements, it is perfect for simple extensions or prefix changes. To create a robust script, you must use proper variable handling to avoid errors during execution. First, open Notepad and save your file with a .bat extension. Inside this file, always begin with setlocal enabledelayedexpansion. This ensures that variables are evaluated correctly inside loops, which is critical when renaming files dynamically. Without this setting, the script may fail to recognize updated filenames during iteration. For basic renaming, such as changing all .txt files to .doc, you can use a straightforward loop:
@echo off
setlocal enabledelayedexpansion

for %%f in (*.txt) do (
    set "name=%%~nf"
    ren "%%f" "!name!.doc"
)
This script iterates through every text file in the current folder, extracts the base name, and applies the new extension. It is essential to test this on a small subset of files first to ensure no data loss occurs. Always back up your files before running bulk operations.

Advanced Pattern Replacement in Windows

If you need to replace specific parts of a filename, such as removing a date stamp or adding a prefix, the native ren command becomes limited. In such cases, PowerShell offers more powerful string manipulation capabilities while still being accessible via a batch wrapper. You can invoke PowerShell from your batch file using powershell -Command. However, for pure batch solutions, you might consider third-party utilities like RENAMER or writing a VBScript helper. These tools provide regex-based renaming which is far superior to the basic wildcard support of ren. If you are already working with Python for other tasks, you might find it easier to integrate file renaming into an existing automation workflow rather than maintaining separate batch logic. For related scripting challenges, see our guide on [Python Script Keeps Closing and Does Not Make a New CSV File](/news/1058932/python-script-closing-and-csv-file-issue).

Linux and macOS Shell Scripts

It is important to clarify that Linux and macOS do not use ".bat" files; they use shell scripts, typically ending in .sh. The primary command for moving or renaming files in these environments is mv. Unlike Windows, the mv command works seamlessly with glob patterns and can handle complex renaming tasks using tools like rename (Perl version) or standard bash loops. To create a shell script, create a new text file and add the shebang line #!/bin/bash at the top. Make the script executable by running chmod +x rename_script.sh in your terminal. Here is a simple example that renames all .jpg files to .png:
#!/bin/bash

for file in *.jpg; do
    if [ -e "$file" ]; then
        mv -- "$file" "${file%.jpg}.png"
    fi
done
The parameter expansion ${file%.jpg} removes the shortest match of .jpg from the end of the variable. This is much safer than hardcoding extensions because it adapts to different filename lengths. Always check if the file exists using [ -e "$file" ] to prevent errors if the glob pattern matches nothing.

Using the Perl Rename Utility

On many Linux distributions, including Ubuntu and Debian, you can install the rename utility (often provided by the perl-rename package). This tool uses Perl regular expressions, allowing for incredibly precise renaming rules. For example, to convert all uppercase letters in filenames to lowercase, you would run:
rename 'y/A-Z/a-z/' *.JPG
This command is non-destructive and highly efficient. It processes files in place without needing explicit loops in your script. macOS users can install this via Homebrew using brew install rename. If you are managing media libraries, you might also encounter issues with video players conflicting with metadata scripts. Understanding how to manage these dependencies is crucial for a smooth workflow, similar to resolving [FFmpeg Causing Sort Conflict with MPV: Script Issue](/news/1322582/ffmpeg-mpv-script-conflict).

Best Practices for Safe Renaming

Regardless of the operating system, safety should be your primary concern when automating file operations. Bulk renaming can accidentally overwrite existing files if two source files resolve to the same target name. Always implement checks to detect potential collisions. One effective strategy is to perform a dry run first. Print the proposed actions instead of executing them. In Windows batch, replace ren with echo ren. In Bash, replace mv with echo mv. Review the output to ensure the logic holds up before committing to the actual operation. Additionally, consider the order of operations. If you are renaming files based on a pattern that overlaps with another rule, process the most specific rules first. For instance, if you have both _temp and _backup suffixes, handle one before the other to avoid partial matches interfering with subsequent steps.

Common Pitfalls to Avoid

A frequent mistake is forgetting to quote filenames containing spaces. In both Windows and Linux scripts, unquoted paths will cause the command interpreter to split the filename at the space, leading to "file not found" errors. Always wrap your variables in quotes, such as "!name!.doc" in Windows or "$file" in Bash. Another pitfall is assuming case-insensitivity where it does not exist. Linux and macOS file systems are typically case-sensitive, meaning File.TXT and file.txt are distinct entities. Windows is generally case-insensitive but preserves the original casing. Be mindful of these differences when migrating scripts between platforms. Finally, avoid hardcoding absolute paths unless necessary. Using relative paths makes your scripts portable and easier to maintain. If you need to reference external resources, ensure the paths are consistent across development and production environments.

Frequently Asked Questions

Can I rename files recursively in subdirectories?

The basic ren command in Windows only works on the current directory. To rename files recursively, you must use for /r in a batch loop or PowerShell's Get-ChildItem -Recurse. On Linux, use find with -exec or the recursive option in the rename utility.

How do I undo a batch rename operation?

There is no automatic "undo" button for bulk file operations. The best practice is to keep a backup copy of your original files before running any script. Some advanced tools offer logging features that record old and new names, allowing you to manually reverse changes if needed.

Why does my script fail with "Access Denied"?

This error usually occurs if a file is currently open in another application, such as Word or Excel. Close all programs that might be locking the files, or run the script as an administrator to gain elevated permissions required for certain system directories.

Is it safe to rename system files?

No, renaming system files can break applications and operating system functionality. Only rename user-generated files in personal directories like Documents or Downloads. Avoid modifying files in C:\Windows or /usr/bin unless you are an expert developer debugging specific issues.

How can I add a timestamp to filenames?

In Windows batch, you can use %date% and %time% variables, though formatting may require additional parsing. In Bash, use $(date +%Y%m%d_%H%M%S) to generate a clean timestamp string that can be appended to your filename variable during the loop.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More