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).
The majority of the other solutions will overwrite existing files already named as a number. This is particularly a problem if running the script, adding more files, and then running the script again.
This script renames existing numerical files first:
with "rename" command
or
Sorted by time, limited to jpg, leading zeroes and a basename (in case you likely want one):
(all on one line, without the
\
)Try to use a loop,
let
, andprintf
for the padding:using the
-i
flag prevents automatically overwriting existing files.I like gauteh's solution for its simplicity, but it has an important drawback. When running on thousands of files, you can get "argument list too long" message (more on this), and second, the script can get really slow. In my case, running it on roughly 36.000 files, script moved approx. one item per second! I'm not really sure why this happens, but the rule I got from colleagues was "
find
is your friend".To count items and build command, gawk was used. Note the main difference, though. By default
find
searches for files in current directory and its subdirectories, so be sure to limit the search on current directory only, if necessary (useman find
to see how).using Pero's solution on OSX required some modification. I used:
note: the backslashes are there for line continuation
edit July 20, 2015: incorporated @klaustopher's feedback to quote the
\"%s\"
argument of themv
command in order to support filenames with spaces.