Build a Bulk File Renaming Tool

Su Suriya Ravichandran Updated 06 Dec 2026
19 min read ·Lesson 196 of 205

This project builds brename.sh, a tool for renaming many files in one command: replacing text in names, changing case, cleaning up spaces, adding prefixes and suffixes, numbering files in sequence and normalizing extensions. Every run first shows a preview. Renames are only performed with -y, and only if none of the new names clashes with another file. Applied runs write an undo script that restores the original names.

Renaming a handful of files by hand is easy. Renaming three hundred photos named IMG 0001.JPG to trip-001.jpg is where a script helps, and also where a script can do real damage: two files that end up with the same new name means one of them is silently overwritten. The core of this project is therefore not the string manipulation, which takes a few lines of parameter expansion, but the plan, check, apply structure around it.

What the Tool Should Do

  1. Operations that can be combined and are applied in the order given:
    • -r FROM=TO replace literal text
    • -l / -u lowercase / uppercase
    • -w turn runs of whitespace into _ and trim them at both ends
    • -p PREFIX and -s SUFFIX
    • -N FORMAT replace the name with a number (-N 'photo-%03d'), starting at 1 or at -i START
    • -e lowercase the extension
  2. Keep the extension out of the way: operations change the part before the last dot, unless they are explicitly about the extension.
  3. Preview by default; -y applies.
  4. All or nothing: if any target name is taken, or two files would get the same name, rename nothing.
  5. Handle chains: renaming ch2.md → ch3.md and ch3.md → ch4.md in one run must work, even though ch3.md exists at the start.
  6. Undo with a generated script.
  7. Any file name, including spaces, newlines, a leading - or shell syntax like $(...), must be handled as plain data.

Design Decisions

Operations as a List

Most command-line tools process options into fixed variables: "lowercase: yes or no". Here the order of operations matters. -p IMG_ -l gives img_holiday, while -l -p IMG_ gives IMG_holiday. The script therefore records each operation in an array as it is parsed, in a compact letter:argument form:

ops=()
while getopts ':r:lus:wp:N:i:eyh' opt; do
    case $opt in
        r)  [[ $OPTARG == ?*=* ]] || die "-r needs FROM=TO with a non-empty FROM" 2
            ops+=("r:$OPTARG") ;;
        l|u|w|e) ops+=("$opt:") ;;
        p|s) ops+=("$opt:$OPTARG") ;;
        ...

For the command brename.sh -r 'IMG =img-' -p 2026- -s _raw, the array becomes r:IMG =img-, p:2026-, s:_raw. Later, a loop walks the array and applies each operation in turn. In the getopts option string, a letter followed by : takes an argument (r:, s:, p:, N:, i:); the others are simple flags.

Applying the Operations

The new_name function first splits the name into a stem and an extension, then transforms the stem:

for op in "${ops[@]}"; do
    arg=${op#?:}
    case $op in
        r:*) from=${arg%%=*}; to=${arg#*=}
             stem=${stem//"$from"/"$to"} ;;
        l:)  stem=${stem,,} ;;
        u:)  stem=${stem^^} ;;
        w:)  stem=${stem//+([[:space:]])/_}
             stem=${stem##+(_)}
             stem=${stem%%+(_)} ;;
        p:*) stem=$arg$stem ;;
        s:*) stem=$stem$arg ;;
        N:*) printf -v stem -- "$arg" "$number" ;;
        e:)  ext=${ext,,} ;;
    esac
done

Every operation is a parameter expansion, with no external commands, which keeps the tool fast even for thousands of files:

  • ${op#?:} removes the operation letter and colon, leaving the argument.
  • ${arg%%=*} and ${arg#*=} split FROM=TO at the first =, so -r 'a=b=c' replaces a with b=c.
  • ${stem//"$from"/"$to"} replaces every occurrence. Quoting "$from" makes Bash treat it as literal text instead of a glob pattern, so -r '*=x' replaces asterisks rather than everything. Quoting "$to" matters in Bash 5.2 and later, where the patsub_replacement option makes an unquoted & in the replacement stand for the matched text.
  • ${stem,,} and ${stem^^} change case (Bash 4 and later).
  • +([[:space:]]) is an extended glob (lesson 153) meaning "one or more whitespace characters", so Holiday Trip becomes Holiday_Trip_ and the trimming expansions remove the underscore at the end. Extended globs must be enabled with shopt -s extglob. The script does this on its first lines, before any function is defined. That is a good habit: for patterns in [[ ]] and case, Bash checks extended glob syntax when it reads the code, so enabling the option later, inside the function, would be too late.
  • printf -v stem -- "$arg" "$number" formats the number into the given pattern and stores it directly in stem. %03d pads with zeros to three digits.

Never Letting printf Interpret Arbitrary Formats

Passing user text to printf as a format is risky in principle: %s without an argument, %n-style conversions in other languages, or %% sequences can produce surprises. The -N option is the only place where this happens, and its argument is validated first:

[[ $OPTARG =~ ^[^%]*%0?[0-9]*d[^%]*$ ]] ||
    die "-N needs a format with exactly one %d, such as 'photo-%03d'" 2

The regular expression allows text, exactly one %d with an optional zero flag and width, and more text, with no other %. Formats like x-%s or %d-%d are rejected before any file is touched. A / is rejected too, since it would move files into another directory.

Splitting Off the Extension

if [[ $name == ?*.* ]]; then      # "my.photo.JPG" -> stem "my.photo", ext ".JPG"
    stem=${name%.*}
    ext=.${name##*.}
fi

%.* removes the shortest suffix starting with a dot, so only the last extension is split off. The pattern ?*.* requires at least one character before the dot, so hidden files like .bashrc keep their whole name as the stem. For a double extension like backup.tar.gz, the stem is backup.tar; a -N rename would turn it into photo-001.gz, so number such files with care.

Plan First, Then Check Everything

The script processes the file list in two separate stages. The planning stage computes every new name and stores the pairs in two arrays, src and dst. Files whose name does not change are left out. Nothing is renamed in this stage.

The checking stage then looks for two kinds of conflict:

for i in "${!dst[@]}"; do
    target=${dst[i]}
    if [[ -n ${seen_dst[$target]:-} ]]; then
        first=${seen_dst[$target]}
        printf 'conflict: %s and %s would both become %s\n' "${src[first - 1]}" "${src[i]}" "$target" >&2
        conflicts=$((conflicts + 1))
    elif [[ -e $target || -L $target ]] && [[ -z ${moving[$target]:-} ]]; then
        printf 'conflict: %s would replace the existing file %s\n' "${src[i]}" "$target" >&2
        conflicts=$((conflicts + 1))
    fi
    seen_dst[$target]=$((i + 1))
done
  1. Two files, one name. The associative array seen_dst remembers every target name already planned, together with the position of its source plus one (so that position 0 is still a non-empty value). A second file planning the same name is a conflict.
  2. Existing files. If the target already exists on disk, it is a conflict, unless that existing file is itself one of the files being renamed in this run (moving). That exception is what allows chains: ch3.md exists, but it is about to become ch4.md, so ch2.md may take its name.

-L is checked as well as -e, because -e follows symbolic links and reports false for a link whose target no longer exists, while the link itself still occupies the name.

The value of seen_dst is copied into first before it is used as an array index. Writing ${src[seen_dst[$target]-1]} would evaluate the file name inside an arithmetic context, and lesson 192 showed that Bash expands command substitutions hidden in array subscripts there. A file named a[$(rm -rf ~)] must stay a harmless string.

If any conflict was found, the script prints the full plan, so the user can see the whole picture, and exits without renaming anything.

Two-Phase Renaming

Even with a conflict-free plan, renaming the files one by one in list order can fail. For the chain ch2.md → ch3.md, ch3.md → ch4.md, the first mv would find ch3.md still in place. A swap (a → b, b → a) cannot be done in any order with direct moves.

The solution is to rename in two phases:

  1. Move every source file to a unique temporary name in its own directory, such as .brename-27736-19206-0.
  2. Move every temporary file to its final name.

After phase 1, none of the original names are occupied by the files being renamed, so every final name is free. The temporary name contains the process ID ($$), a random number and the file's position, and starts with a dot so it stays out of sight in normal listings. Keeping the temporary file in the same directory matters: a rename within one directory is a single atomic operation in the file system, while a move to another file system would copy the data.

If phase 1 fails halfway, for example because one directory is read-only, the script moves the files that were already renamed back to their original names and stops:

if ! mv -n -- "${src[i]}" "${tmp[i]}"; then
    for (( j = i - 1; j >= 0; j-- )); do       # roll back phase 1
        mv -n -- "${tmp[j]}" "${src[j]}"
    done
    die "could not move ${src[i]}: nothing was renamed"
fi

All mv calls use -n (never overwrite) and -- (end of options), so a file named -v.TXT is a name and not an option.

An Undo Script That Quotes Everything

After applying, the tool writes a small Bash script that reverses the renames, again in two phases. Every file name in it is written with printf %q, which produces a quoted form that Bash reads back as exactly the same string:

for i in "${!src[@]}"; do printf 'mv -n -- %q %q\n' "${dst[i]}" "${tmp[i]}"; done
for i in "${!src[@]}"; do printf 'mv -n -- %q %q\n' "${tmp[i]}" "${src[i]}"; done

A name like $(touch PWNED) x.TXT becomes \$0touch\ PWNED1\ x.TXT, and a name containing a newline becomes $'line\nbreak.TXT'. Generating code from data is only safe with this kind of quoting; inserting names into the script with plain "$name" would turn a hostile file name into a command the moment the undo script runs (lesson 156).

The undo scripts are stored in ${XDG_STATE_HOME:-$HOME/.local/state}/brename/, the standard location for application state on Linux, not in the directory being renamed. Otherwise the next brename.sh ... * would pick up the undo script as one of the files to rename.

The Complete Script

#!/usr/bin/env bash
#
# brename.sh - rename many files at once, safely
#
# Usage: brename.sh [OPERATION...] [-y] FILE...
#
# Operations (applied to the name without its extension, in the order given):
#   -r FROM=TO   replace every FROM with TO (literal text, not a pattern)
#   -l           convert to lowercase
#   -u           convert to uppercase
#   -w           replace runs of spaces with "_" and trim them at both ends
#   -p PREFIX    add PREFIX at the start
#   -s SUFFIX    add SUFFIX at the end (before the extension)
#   -N FORMAT    replace the name with a numbered one, e.g. -N 'photo-%03d'
#   -i START     first number for -N (default: 1)
#   -e           convert the extension to lowercase
#
# Other options:
#   -y           apply the renames (without -y, only a preview is shown)
#   -h           show this help
#
# Nothing is renamed if any new name clashes with another file. Applied runs
# write an undo script to ${XDG_STATE_HOME:-~/.local/state}/brename/.
#
# Exit status: 0 success, 1 conflict or failed rename, 2 usage error.

set -euo pipefail
shopt -s extglob                      # for +( ) patterns in new_name

readonly PROG=${0##*/}

usage() { sed -n '3,27s/^# \{0,1\}//p' "$0"; }

die() {
    printf '%s: %s\n' "$PROG" "$1" >&2
    exit "${2:-1}"
}

ops=()                                # operations in command-line order
apply=0
start=1
while getopts ':r:lus:wp:N:i:eyh' opt; do
    case $opt in
        r)  [[ $OPTARG == ?*=* ]] || die "-r needs FROM=TO with a non-empty FROM" 2
            ops+=("r:$OPTARG") ;;
        l|u|w|e) ops+=("$opt:") ;;
        p|s) ops+=("$opt:$OPTARG") ;;
        N)  [[ $OPTARG =~ ^[^%]*%0?[0-9]*d[^%]*$ ]] ||
                die "-N needs a format with exactly one %d, such as 'photo-%03d'" 2
            [[ $OPTARG != */* ]] || die "-N format may not contain '/'" 2
            ops+=("N:$OPTARG") ;;
        i)  [[ $OPTARG =~ ^[0-9]+$ ]] || die "-i needs a whole number" 2
            start=$((10#$OPTARG)) ;;
        y)  apply=1 ;;
        h)  usage; exit 0 ;;
        :)  die "option -$OPTARG needs a value" 2 ;;
        *)  die "unknown option -$OPTARG (try -h)" 2 ;;
    esac
done
shift $((OPTIND - 1))

(( ${#ops[@]} > 0 )) || die "no operation given (try -h)" 2
(( $# > 0 ))         || die "no files given (try -h)" 2

# new_name NAME NUMBER - apply every operation to one file name
new_name() {
    local name=$1 number=$2 stem ext="" op arg from to
    stem=$name
    if [[ $name == ?*.* ]]; then      # "my.photo.JPG" -> stem "my.photo", ext ".JPG"
        stem=${name%.*}
        ext=.${name##*.}
    fi
    for op in "${ops[@]}"; do
        arg=${op#?:}
        case $op in
            r:*) from=${arg%%=*}; to=${arg#*=}
                 stem=${stem//"$from"/"$to"} ;;
            l:)  stem=${stem,,} ;;
            u:)  stem=${stem^^} ;;
            w:)  stem=${stem//+([[:space:]])/_}
                 stem=${stem##+(_)}
                 stem=${stem%%+(_)} ;;
            p:*) stem=$arg$stem ;;
            s:*) stem=$stem$arg ;;
            N:*) printf -v stem -- "$arg" "$number" ;;
            e:)  ext=${ext,,} ;;
        esac
    done
    printf '%s%s\n' "$stem" "$ext"
}

# --- plan: compute every new name and check for conflicts --------------------------

declare -a src=() dst=()
declare -A seen_src=() moving=() seen_dst=()
number=$((start - 1))
for path in "$@"; do
    [[ -e $path || -L $path ]] || die "no such file: $path" 2
    [[ -z ${seen_src[$path]:-} ]] || die "file given twice: $path" 2
    seen_src[$path]=1
    number=$((number + 1))

    name=${path##*/}
    prefix=${path%"$name"}                           # "photos/" or ""
    new=$(new_name "$name" "$number")
    [[ $new == "$name" ]] && continue                  # nothing to do

    [[ -n $new && $new != . && $new != .. && $new != */* ]] ||
        die "operations turn '$name' into an invalid name '$new'"
    src+=("$path")
    moving[$path]=1
    dst+=("$prefix$new")
done

(( ${#src[@]} > 0 )) || { echo "nothing to rename: every name is already as requested"; exit 0; }

conflicts=0
for i in "${!dst[@]}"; do
    target=${dst[i]}
    if [[ -n ${seen_dst[$target]:-} ]]; then
        first=${seen_dst[$target]}
        printf 'conflict: %s and %s would both become %s\n' "${src[first - 1]}" "${src[i]}" "$target" >&2
        conflicts=$((conflicts + 1))
    elif [[ -e $target || -L $target ]] && [[ -z ${moving[$target]:-} ]]; then
        printf 'conflict: %s would replace the existing file %s\n' "${src[i]}" "$target" >&2
        conflicts=$((conflicts + 1))
    fi
    seen_dst[$target]=$((i + 1))
done

for i in "${!src[@]}"; do
    printf '%s  ->  %s\n' "${src[i]}" "${dst[i]##*/}"
done

(( conflicts == 0 )) || die "$conflicts conflict(s): nothing was renamed"

if (( ! apply )); then
    printf '\n%d file(s) would be renamed. Run again with -y to apply.\n' "${#src[@]}"
    exit 0
fi

# --- apply in two phases, so chains (a->b, b->c) and swaps (a<->b) work ---------------

tag=.brename-$$-$RANDOM
tmp=()
for i in "${!src[@]}"; do
    name=${src[i]##*/}
    tmp[i]=${src[i]%"$name"}$tag-$i
    if ! mv -n -- "${src[i]}" "${tmp[i]}"; then
        for (( j = i - 1; j >= 0; j-- )); do       # roll back phase 1
            mv -n -- "${tmp[j]}" "${src[j]}"
        done
        die "could not move ${src[i]}: nothing was renamed"
    fi
done
failed=0
for i in "${!src[@]}"; do
    if ! mv -n -- "${tmp[i]}" "${dst[i]}" || [[ -e ${tmp[i]} ]]; then
        printf '%s: could not rename to %s, left as %s\n' "$PROG" "${dst[i]}" "${tmp[i]}" >&2
        failed=$((failed + 1))
    fi
done

# --- undo script --------------------------------------------------------------------

undo_dir=${XDG_STATE_HOME:-$HOME/.local/state}/brename
mkdir -p -- "$undo_dir"
undo=$undo_dir/undo-$(date +%Y%m%d-%H%M%S)-$$.sh
{
    printf '#!/usr/bin/env bash\n'
    printf '# undo for: %s\n' "$(date '+%Y-%m-%d %H:%M:%S')"
    printf 'set -e\ncd %q\n' "$PWD"
    for i in "${!src[@]}"; do printf 'mv -n -- %q %q\n' "${dst[i]}" "${tmp[i]}"; done
    for i in "${!src[@]}"; do printf 'mv -n -- %q %q\n' "${tmp[i]}" "${src[i]}"; done
} > "$undo"
chmod +x "$undo"

printf '\nrenamed %d file(s); to undo, run: %q\n' "$(( ${#src[@]} - failed ))" "$undo"
(( failed == 0 ))

Using the Tool

Preview and Apply

Starting with four badly named files:

$ ls
'Holiday  Trip .JPG'  'IMG 0001.JPG'  'IMG 0002.JPG'   notes.TXT
$ brename.sh -w -l -e *
Holiday  Trip .JPG  ->  holiday_trip.jpg
IMG 0001.JPG  ->  img_0001.jpg
IMG 0002.JPG  ->  img_0002.jpg
notes.TXT  ->  notes.txt

4 file(s) would be renamed. Run again with -y to apply.

The preview shows the effect of each operation: -w turned the spaces into underscores and dropped the trailing space of Holiday Trip , -l lowercased the stems and -e the extensions. Nothing has changed yet. Adding -y performs the renames:

$ brename.sh -w -l -e -y *
Holiday  Trip .JPG  ->  holiday_trip.jpg
IMG 0001.JPG  ->  img_0001.jpg
IMG 0002.JPG  ->  img_0002.jpg
notes.TXT  ->  notes.txt

renamed 4 file(s); to undo, run: /home/suriya/.local/state/brename/undo-20261202-171315-27652.sh
$ ls
holiday_trip.jpg  img_0001.jpg  img_0002.jpg  notes.txt

Undoing

The generated undo script reverses the renames in two phases:

$ cat ~/.local/state/brename/undo-20261202-171315-27652.sh
#!/usr/bin/env bash
# undo for: 2026-12-02 17:13:15
set -e
cd /home/suriya/photos
mv -n -- holiday_trip.jpg .brename-27652-19206-0
mv -n -- img_0001.jpg .brename-27652-19206-1
mv -n -- img_0002.jpg .brename-27652-19206-2
mv -n -- notes.txt .brename-27652-19206-3
mv -n -- .brename-27652-19206-0 Holiday\ \ Trip\ .JPG
mv -n -- .brename-27652-19206-1 IMG\ 0001.JPG
mv -n -- .brename-27652-19206-2 IMG\ 0002.JPG
mv -n -- .brename-27652-19206-3 notes.TXT
$ ~/.local/state/brename/undo-20261202-171315-27652.sh
$ ls
'Holiday  Trip .JPG'  'IMG 0001.JPG'  'IMG 0002.JPG'   notes.TXT

The script changes to the original directory first, so it works from wherever it is run, and set -e stops it at the first failure.

Numbering Files

-N replaces the stem with a number. The extension is kept, here lowercased with -e:

$ brename.sh -N 'trip-%03d' -e IMG*.JPG 'Holiday  Trip .JPG'
IMG 0001.JPG  ->  trip-001.jpg
IMG 0002.JPG  ->  trip-002.jpg
Holiday  Trip .JPG  ->  trip-003.jpg

3 file(s) would be renamed. Run again with -y to apply.

The numbers follow the order of the arguments. That order needs attention when names contain numbers without leading zeros, because the shell sorts glob results as text:

$ brename.sh -N 'photo-%02d' img*.jpg
img1.jpg  ->  photo-01.jpg
img10.jpg  ->  photo-02.jpg
img2.jpg  ->  photo-03.jpg

img10 sorts before img2 because 1 comes before 2. GNU sort -V ("version sort") compares the digit sequences as numbers. Combined with NUL-separated names (lesson 112), it produces the intended order:

$ printf '%s\0' img*.jpg | sort -zV | xargs -0 brename.sh -N 'photo-%02d'
img1.jpg  ->  photo-01.jpg
img2.jpg  ->  photo-02.jpg
img10.jpg  ->  photo-03.jpg

Combining Operations

Operations run in the order given. Here a literal replacement turns IMG (with its space) into img-, then a prefix and a suffix are added around the stem:

$ brename.sh -r 'IMG =img-' -p 2026- -s _raw IMG*
IMG 0001.JPG  ->  2026-img-0001_raw.JPG
IMG 0002.JPG  ->  2026-img-0002_raw.JPG

2 file(s) would be renamed. Run again with -y to apply.

Renaming Along a Chain

A book has chapters ch1.md, ch2.md and ch3.md, and a new chapter must be inserted as chapter 2. The existing chapters 2 and 3 have to become 3 and 4:

$ brename.sh -N 'ch%d' -i 3 -y book/ch2.md book/ch3.md
book/ch2.md  ->  ch3.md
book/ch3.md  ->  ch4.md

renamed 2 file(s); to undo, run: /home/suriya/.local/state/brename/undo-20261202-171332-27736.sh
$ for f in book/*; do printf '%s: %s\n' "$f" "$(cat "$f")"; done
book/ch1.md: chapter 1
book/ch3.md: chapter 2
book/ch4.md: chapter 3

ch3.md existed when the run started, but it was part of the batch, so the plan was accepted, and the two-phase rename made it work. The file contents prove that no chapter was overwritten.

Conflicts Stop Everything

Two files that would get the same name:

$ brename.sh -r '0001=X' -r '0002=X' IMG*; echo "status $?"
conflict: IMG 0001.JPG and IMG 0002.JPG would both become IMG X.JPG
IMG 0001.JPG  ->  IMG X.JPG
IMG 0002.JPG  ->  IMG X.JPG
brename.sh: 1 conflict(s): nothing was renamed
status 1

A target name that belongs to a file outside the batch:

$ ls notes*
notes.TXT  notes.txt
$ brename.sh -e notes.TXT; echo "status $?"
conflict: notes.TXT would replace the existing file notes.txt
notes.TXT  ->  notes.txt
brename.sh: 1 conflict(s): nothing was renamed
status 1

On a case-sensitive file system like Linux ext4, notes.TXT and notes.txt are different files, and a plain mv would have destroyed notes.txt.

Hostile File Names

File names are data, never code. A name containing a command substitution, a name containing a newline and a name that looks like an option all pass through the rename and the undo unchanged, and the embedded command never runs:

$ touch 'w/$(touch PWNED) x.TXT' $'w/line\nbreak.TXT' 'w/-v.TXT'
$ brename.sh -e -y w/* > /dev/null
$ ls w | cat -A
$(touch PWNED) x.txt$
-v.txt$
line$
break.txt$
$ ls PWNED
ls: cannot access 'PWNED': No such file or directory

A Failure in the Middle

If one of the directories cannot be written to, the rename of that file fails in phase 1, and the files already moved are put back. Here the test ran as an unprivileged user, with rb/locked set to read-only:

$ brename.sh -e -y rb/a.TXT rb/locked/b.TXT rb/c.TXT; echo "status $?"
rb/a.TXT  ->  a.txt
rb/locked/b.TXT  ->  b.txt
rb/c.TXT  ->  c.txt
mv: cannot move 'rb/locked/b.TXT' to 'rb/locked/.brename-27915-2070-1': Permission denied
brename.sh: could not move rb/locked/b.TXT: nothing was renamed
status 1
$ ls rb
a.TXT  c.TXT  locked

a.TXT had already been moved to its temporary name; the rollback restored it.

Input Errors

$ brename.sh IMG*
brename.sh: no operation given (try -h)
$ brename.sh -N 'x-%s' IMG*
brename.sh: -N needs a format with exactly one %d, such as 'photo-%03d'
$ brename.sh -r 'IMG=a/b' IMG*
brename.sh: operations turn 'IMG 0001.JPG' into an invalid name 'a/b 0001.JPG'
$ brename.sh -l notes.TXT notes.TXT
brename.sh: file given twice: notes.TXT

Usage errors exit with status 2; conflicts and failed renames with status 1.

Comparison with Other Tools

Linux distributions ship two different commands named rename. The util-linux version (rename FROM TO FILES) performs a single literal replacement. The Perl version, called rename on Debian and Ubuntu and prename or perl-rename elsewhere, accepts a Perl expression such as rename 's/0JPG$/.jpg/' * and has a -n dry-run option. Both are useful for quick jobs. brename.sh adds what neither offers by default: refusing the whole batch on any conflict, chains and swaps, numbering, and an undo script. Writing it yourself also shows exactly what a safe rename involves.

Ideas for Extending the Project

  • Regular expressions. Add -R REGEX=REPLACEMENT using [[ $stem =~ $regex ]] and BASH_REMATCH to build names from captured groups, for example turning report_2026_12.pdf into 2026-12-report.pdf.
  • Recursion. Accept directories with -R and collect files with find -print0, renaming the deepest entries first so that directory renames do not invalidate the paths of files inside them.
  • Date-based names. Add an operation that inserts the file's modification date (date -r FILE +%F) or, for photos, the date stored in the EXIF data via exiftool.
  • Transliteration. Replace characters that cause trouble on other systems (accented letters, : on Windows) with iconv -f utf-8 -t ascii//TRANSLIT.
  • Tests. The preview mode makes the tool easy to test with Bats (lesson 185): assert on the planned names without touching files, and test conflicts and chains in a temporary directory.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Build a Bulk File Renaming Tool and get answers drawn from it.

Signed-in readers only.