Batch-Rename Files by Extension Across a Directory Tree
A camera card with 500 photos sounds manageable until you find half of them saved as .JPG and the other half as .jpg. On Linux those are two different extensions: a tool that globs *.jpg silently skips every uppercase file, and a batch pipeline fails halfway through without ever saying why. The fix is a short bash script that walks a directory tree, renames every file from one extension to another, and prints each change as it happens so you can audit the whole run afterwards.
The script below takes three arguments — a root directory, an old extension and a new extension — and does exactly that: recursive, safe on weird filenames, and loud about what it did. It was verified in a clean Ubuntu container with a 16-assertion test harness covering nested trees, spaces, unicode names and a 500-file stress run.

Why extension case actually matters
File extensions are metadata that tools read, and most tools read them exactly as written. Linux filesystems (ext4, btrfs, xfs) are case-sensitive, so photo.JPG, photo.jpg and Photo.Jpg can all sit in the same directory side by side. Windows and macOS default filesystems are case-insensitive, which is how mixed-case names end up on a machine in the first place — copy files across platforms, export from a Windows share, or pull photos off a camera that uppercases its extensions, and your tree ends up with a mix.
The trouble shows up the moment something matches on one specific case. An image pipeline that processes *.jpg skips the uppercase half. A log rotation script watching /var/log/app/*.log misses every .LOG file a Windows agent wrote. A backup job that archives *.bak leaves .BAK files behind. None of these failures produce an error — they just quietly do less work than you asked, and you only notice when the output is short by half.
Normalising extensions to one case is a five-minute fix that removes an entire class of those silent skips. Doing it by hand across hundreds of files in nested folders is not.
How it works
The guards
The script starts with set -euo pipefail, then checks its arguments before touching anything. Three flags do real work: -e aborts on any non-zero exit, -u treats unset variables as errors (so a blank extension can never become a rename target), and -pipefail makes a pipeline fail if any command in it fails. For a script about to run mv hundreds of times, you want it to stop the moment something goes wrong — not plough through and leave a half-renamed tree.
The argument check requires exactly three positional arguments or prints usage to stderr and exits 1. The ${2#.} and ${3#.} strips remove a leading dot if you supplied one, so .jpg and jpg mean the same thing — nobody should have to remember whether the dot is part of the extension.
Two more guards follow. If old and new extension are identical, the script refuses to run: without this check it would rename every file onto itself and print hundreds of foo.jpg -> foo.jpg lines that changed nothing. And if the root path doesn't exist or isn't a directory, it bails with a clear message instead of letting find fail mid-loop, which would leave you wondering whether 300 files were processed or 499.
The rename loop
The core is one while loop reading from process substitution:
done < <(find "$dir" -type f -name "*.${old_ext}" -print0)
Two details in that line matter. -type f restricts matches to regular files, so symlinks and directories are never touched. -print0 ends each path with a NUL byte instead of a newline, and the loop reads it back with read -r -d '' — together they handle filenames containing spaces, newlines or any other shell-hostile character. A plain newline-delimited loop would split a file called my photo (1).JPG into two broken paths.
Inside the loop, ${file%.*} strips everything from the last dot onward, leaving the basename without its extension; the new extension is appended and mv -- performs the rename (the -- protects against filenames that start with a dash). A printf line prints old -> new for every change — your audit trail — and a counter increments. When the loop finishes, the script reports the total.
Verification
The script was verified in a clean Ubuntu container with no network access: the script and its test harness are mounted read-only into /work, and the harness builds fresh fixture trees under /tmp for each test. Six test groups produce 16 assertions:
- Flat rename — two
.JPGfiles renamed, a.jpgand a.pngleft untouched, uppercase originals gone. - Deep nesting and hostile names — a file five directories down, one with spaces in the name, one with a unicode character (
π), plus.jpegand mixed-case.Jpgfiles that must not match a case-sensitive.JPGsearch. - No matches — a directory with no matching files reports
Renamed 0 file(s).and exits cleanly. - Missing arguments — the script exits non-zero and prints its usage line.
- Bad directory — a non-existent path exits non-zero with an explicit error.
- Stress — 500
.JPGfiles spread across 20 subdirectories, all renamed, zero uppercase files remaining.
A sample of the real output from the hostile-names run:
/tmp/testdata/t2/a/unicode_π.JPG -> /tmp/testdata/t2/a/unicode_π.jpg
/tmp/testdata/t2/a/b/with spaces.JPG -> /tmp/testdata/t2/a/b/with spaces.jpg
/tmp/testdata/t2/a/b/c/d/e/deep.JPG -> /tmp/testdata/t2/a/b/c/d/e/deep.jpg
Renamed 3 file(s).
The guard rails fire as designed when the script is called wrong:
Usage: /work/rename_ext.sh <directory> <old_ext> <new_ext>
Error: '/tmp/testdata/does_not_exist' is not a directory
And the 500-file stress run ends with every change listed, one per line, followed by the summary and the harness result:
/tmp/testdata/t6/d0/img_500.JPG -> /tmp/testdata/t6/d0/img_500.jpg
...
Renamed 500 file(s).
Results: 16 passed, 0 failed
The script
#!/usr/bin/env bash
set -euo pipefail
if [ $# -ne 3 ]; then
echo "Usage: $0 <directory> <old_ext> <new_ext>" >&2
exit 1
fi
dir="$1"
old_ext="${2#.}"
new_ext="${3#.}"
if [ "$old_ext" = "$new_ext" ]; then
echo "Error: old and new extension are identical ('$old_ext')" >&2
exit 1
fi
if [ ! -d "$dir" ]; then
echo "Error: '$dir' is not a directory" >&2
exit 1
fi
count=0
while IFS= read -r -d '' file; do
new_file="${file%.*}.${new_ext}"
mv -- "$file" "$new_file"
printf '%s -> %s\n' "$file" "$new_file"
count=$((count + 1))
done < <(find "$dir" -type f -name "*.${old_ext}" -print0)
echo "Renamed $count file(s)."
How to use it
Basic invocation
Save the script as rename_ext.sh, make it executable, and pass a directory plus two extensions. The leading dot is optional on both:
chmod +x rename_ext.sh
./rename_ext.sh /path/to/photos .JPG jpg
That renames every .JPG file under /path/to/photos — recursively, through every subdirectory — to .jpg, printing each change as it goes.
Real-world examples
# Normalise .LOG files from a Windows agent to lowercase .log
./rename_ext.sh /var/log/app LOG log
# Rename .bak config backups to .backup after a migration
./rename_ext.sh /etc/myapp/backup bak backup
# Fix mixed-case .TXT exports copied off a Windows share
./rename_ext.sh /mnt/windows_share TXT txt
Preview before you commit
For a large tree, count what will change before you rename anything:
find /data/photos -type f -name "*.JPG" | wc -l
Then run the script and keep its output as an audit log — every line is one rename, so the file doubles as a change record if you ever need to reverse the batch:
./rename_ext.sh /data/photos JPG jpg > /tmp/rename_audit.log 2>&1
Caveats
Two behaviours deserve a plain warning. First, the script does not check whether the target name already exists: if img_001.jpg is present and you rename img_001.JPG, mv overwrites it silently. On a case-sensitive Linux filesystem that collision can only happen when both names really do coexist — but when they do, the existing file is gone. For destructive batches, take a backup first.
Second, this script assumes a case-sensitive filesystem. On Windows or a default macOS volume, .JPG and .jpg refer to the same filename space, so the collision above is the normal state rather than an edge case — which also means there is usually nothing to rename in the first place. If you find both cases on such a system, sort out which name your tools expect before running anything.
The good news: when nothing matches, the script is a safe no-op. It prints Renamed 0 file(s)., changes nothing and exits 0 — so pointing it at a directory that is already clean costs you nothing.