Rename all files in a folder to consecutive numbers
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
Here's a small python script that can do what you ask
Basic usage:
python rename_files.py Pictures/
It will print output to stdout
before renaming each file
This version pushes index until it is found that filename with such index is not taken. Although filenames may start at different index upon successive iterations of the script, the files themselves remain unchanged.
import os
import sys
top_dir = os.path.abspath(sys.argv[1])
files = os.listdir( top_dir )
for index,item in enumerate(files):
if os.path.isdir( os.path.join(top_dir,item) ):
files.pop(index)
files.sort()
duplicates = []
last_index = None
for index,item in enumerate(files):
last_index = index
extension = ""
if '.' in item:
extension = '.' + item.split('.')[-1]
old_file = os.path.join(top_dir,item)
new_file = os.path.join(top_dir,str(index) + extension )
while os.path.isfile(new_file):
last_index += 1
new_file = os.path.join(top_dir,str(last_index) + extension )
print( old_file + ' renamed to ' + new_file )
os.rename(old_file,new_file)
Alternative version, solves issue with duplicate filenames by appending timestamp to each filename, and then enumerating them. This solution may take longer time, as number of files increases, but for directories that range in hundreds , this won't take long time
import os
import sys
import time
top_dir = os.path.abspath(sys.argv[1])
files = os.listdir( top_dir )
for index,item in enumerate(files):
if os.path.isdir( os.path.join(top_dir,item) ):
files.pop(index)
files.sort()
timestamp = str(int(time.time()))
for item in files:
os.rename( os.path.join(top_dir,item) ,
os.path.join(top_dir, timestamp + item) )
files2 = os.listdir( top_dir )
for index,item in enumerate(files2):
if os.path.isdir( os.path.join(top_dir,item) ):
files2.pop(index)
for index,item in enumerate( files2 ):
last_index = index
extension = ""
if '.' in item:
extension = '.' + item.split('.')[-1]
old_file = os.path.join(top_dir,item)
new_file = os.path.join(top_dir,str(index) + extension )
while os.path.isfile(new_file):
last_index += 1
new_file = os.path.join(top_dir,str(last_index) + extension )
print( old_file + ' renamed to ' + new_file )
os.rename(old_file,new_file)