I have a set of files that I need to rename based on the creation time, by appending two digits to the beginning indicating the sequence.

Say, I have the following files:

Filename         Creation time
api.c            00:15
helloworld.h     00:05
ubuntu.iso       00:10

After renaming, the filenames should be of the form:


How should I go about doing this?

  • 2
    Do you have the creation times stored anywhere, or should it be read from the file (if so, would the modify time do)? – Jacob Vlijm Mar 6 '17 at 17:31
  • What creation time? Unix doesn't have that by default. – thrig Mar 6 '17 at 17:31

This pipes into less also bash assumed.

ls -tr prints files oldest modified first, others have commented on creation time.

a=0, ls -tr | while read line; do printf "%s \'%s\' \'%03d_%s\'\n" mv "$line" $((a=a + 1)) "$line"; done|less
  • 2
    ... and to actually have this working, do something like a=0, ... ; done | bash ? – user2064000 Mar 6 '17 at 19:43

With zsh:

( autoload zmv
set -- *(.Om)
zmv -n -Q '*(.Om)' '${(l:${pad}::0:)$((++i))}_$f' )

This gets the number of files first (to be able to calculate the length for zero padding via the l flag) then renames them using zmv with -Q to take advantage of the glob qualifiers .Om which select only regular files and sort them by their mtime.
Remove the -n (the dry-run switch) if you're happy with the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.