A small, portable Bash script that batch‑renames files by substituting a token in each filename with a replacement value taken from a two‑column mapping table.
Why another renamer?
• Works with any file type.
• Dry‑run by default (zero‑risk).
• Handles Windows line endings automatically.
• Only a Bash ≥ 4 shell required—no external dependencies.
# Preview renames (recommended)
./rename_by_map.sh -m mapping.tsv -g "*.cov"
# If preview looks correct, apply changes
./rename_by_map.sh -m mapping.tsv -g "*.cov" --apply
Flag | Purpose | Default |
---|---|---|
-m FILE |
Mapping file (two whitespace‑separated columns) | required |
-d DIR |
Directory to process | . |
-g GLOB |
Shell glob restricting which files are touched | * |
--apply |
Perform renames (omit for dry‑run) | false |
oldToken newToken
ind01 GTEX-1IL2V
ind02 GTEX-15DDE
IMG0001 Vacation_0001
Tabs or spaces both work.
Windows CRLF endings are stripped automatically.
Goal | Command |
---|---|
Rename Black_ind??_chr*.cov to GTEx IDs |
./rename_by_map.sh -m ind_map.txt -g "Black_*.cov" --apply |
Rename all FASTQ files in /data/run42 |
./rename_by_map.sh -d /data/run42 -m sample_map.tsv -g "*.fq.gz" --apply |
Preview renaming JPEGs in images/ |
./rename_by_map.sh -d images -m pic_map.txt -g "*.jpg" |
mv -v -- 'Black_ind03_chr14.cov' 'Black_GTEX-13SLX_chr14.cov'
mv -v -- 'Black_ind03_chr15.cov' 'Black_GTEX-13SLX_chr15.cov'
…
‘Black_ind03_chr14.cov’ -> ‘Black_GTEX-13SLX_chr14.cov’
‘Black_ind03_chr15.cov’ -> ‘Black_GTEX-13SLX_chr15.cov’
…
Symptom | Likely cause / fix |
---|---|
⚠️ No mapping found for … |
Filename lacks a token present in the map. Add the mapping or ignore. |
Garbled preview lines | Hidden \r in mapping file; clean with dos2unix or rely on built‑in stripping. |
“No key/value pairs found” | Mapping file mis‑formatted or empty. |
- Load mapping: Reads
MAPFILE
into an associative array (map[key]=value
), stripping\r
and trailing whitespace. - Scan files:
cd DIR
and iterate overGLOB
. - Substitute: For each filename, replace the first matching key with its value.
- Dry‑run v. live: Without
--apply
, printsmv
commands; with it, executes them. - Safety nets:
set -euo pipefail
+ warnings for unmapped keys.
- Bash ≥ 4 (associative arrays).
- Standard POSIX tools (
mv
,printf
). - Linux, macOS, or any UNIX‑like environment (WSL, Git‑Bash on Windows).
MIT – © 2025 C J & Contributors. Feel free to adapt and redistribute.
nice utility