Ubuntu – Rename all files in a folder to consecutive numbers

command linerename

I would like to rename all files in a folder so to have consecutive numbers. For instance:

1.png
2.png
3.png
etc

I know there is the rename command and I know there are DOZENS of similar questions in here but I can't find the way.

NOTE: Suggested duplicate doesn't contain a solution specific for my case. Please stop flagging this as duplicate, because suggested duplicate does not answer my question

Best Answer

Assuming you want to follow the shell globbing order while sorting files, you can do:

#!/bin/bash
counter=0
for file in *; do 
    [[ -f $file ]] && echo mv -i "$file" $((counter+1)).png && ((counter++))
done

Here looping over all the files in the current directory and renaming sequentially based on order, if you want to deal with only the .png files, use for file in *.png instead. counter variable will keep track of the increments.

This is a dry-run, remove echo to let the actual renaming action take place.

Example:

$ counter=0; for file in *; do [[ -f $file ]] && echo mv -i "$file" $((counter+1)).png && ((counter++)); done
mv -i file.txt 1.png
mv -i foo.sh 2.png
mv -i bar.txt 3.png