bash command rename file in a new filename numbers natural
Here are the most common and practical bash ways to rename files to sequential natural numbers (1, 2, 3, …), usually with leading zeros so they sort correctly (natural / version sort friendly).
1. Simplest & most reliable (bash loop + printf padding)
Bash
i=1
for file in *; do
# Skip directories if you only want files
[[ -f "$file" ]] || continue
ext="${file##*.}"
new=$(printf "%04d.%s" "$i" "$ext") # %04d = 4 digits with leading zeros
mv -i -- "$file" "$new"
((i++))
done- Change %04d to %03d, %05d, etc. depending how many digits you need.
- Use -n instead of -i if you don’t want interactive overwrite confirmation.
- To sort by name naturally first (recommended): replace * with $(ls -v) or $(ls | sort -V)
2. One-liner version (very popular)
Bash
n=1; for f in *; do [[ -f "$f" ]] && mv -i -- "$f" "$(printf "%04d.${f##*.}" $((n++)))"; done3. Sort by modification time (newest gets highest number)
Bash
n=1
for f in $(ls -t); do # -t = newest first
[[ -f "$f" ]] || continue
mv -i -- "$f" "$(printf "%04d.${f##*.}" $n)"
((n++))
doneReverse order (oldest first = 0001):
Bash
n=1
for f in $(ls -tr); do ... # -tr = oldest first4. Using Perl rename command (very powerful, often pre-installed on Ubuntu/Debian)
Bash
# Number all .jpg files, padded to 4 digits
rename -n 'our $i; s/.*/sprintf("%04d.jpg", ++$i)/e' *.jpgRemove -n (dry-run) when you’re ready to really rename.
Alternative syntax (keeps original extension):
Bash
rename -n 'our $i; s/.+/sprintf("%04d", ++$i) . "." . $&/e' *5. Using ls -v (natural sort) + cat -n style
Bash
ls -v | cat -n | while read -r num name; do
[[ -f "$name" ]] || continue
mv -i -- "$name" "$(printf "%04d.${name##*.}" "$num")"
done- ls -v → natural/version sort (1, 2, …, 10, 11 instead of 1, 10, 11, 2)
Quick recommendations
| Goal | Recommended command style |
|---|---|
| Natural alphabetical order | Use ls -v or sort -V |
| By date (newest last) | ls -tr |
| Keep original extension | Use ${file##*.} or .${f#*.} |
| Want prefix? (photo_0001.jpg) | printf «photo_%04d.${f##*.}» $n |
| Don’t want padding? | Use %d instead of %04d |
| Just want to see what happens | Add echo before mv or use rename -n |
Warning: Always test first with echo or -n flag. Run these in a folder with copies of your files.
What's your reaction?
Excited
0Happy
0In Love
0Not Sure
0Silly
0










