I want to rename the files in a directory to sequential numbers. Based on creation date of the files.
For Example sadf.jpg
to 0001.jpg
, wrjr3.jpg
to 0002.jpg
and so on, the number of leading zeroes depending on the total amount of files (no need for extra zeroes if not needed).
Try to use a loop, let
, and printf
for the padding:
a=1
for i in *.jpg; do
new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
mv -i -- "$i" "$new"
let a=a+1
done
using the -i
flag prevents automatically overwriting existing files.
You can also do
printf -v new "%04d.jpg" ${a}
to put the value into the variable. And((a++))
works to increment the variable. Also, this doesn't do it in creation date order or minimize the padding which are things the OP specified. However, it should be noted that Linux/Unix don't store a creation date.Needed to double quote wrap the mv for this to work in my bash environment. mv "${i}" "${new}"
Could just be Cygwin (although it's terminal behaviour is largely identical to normal Unix shells) but it seems to have a problem when there are spaces in the filename.
It would probably also be desirable to use
mv -- "$i" "$new"
to correctly handle source filenames that start with dashes; as it is,mv
will try to parse such filenames as collections of flags.I have lost about 800 files at a glimpse. I think
-i
should be included in the answer and note should be rewritten accordingly. that'll be more safe. :(