Paul Paul -4 years ago 143
Linux Question

Sort and rename files using a 9 digit sequence number

I want to rename multiple jpg files in a directory so they have 9 digit sequence number. I also want the files to be sorted by date from oldest to newest. I came up with this:

ls -tr | nl -v 100000000 | while read n f; do mv "$f" "$n.jpg"; done

this renames the files as I want them but the sequence numbers do not follow the date. I have also tried doing

ls -tr | cat -n .....

but that does not allow me to sepecify the starting sequence number.
Any suggestions what's wrong with my syntax?
Any other ways of achieving my goal?

Answer Source

If any of your filename contains a whitespace, you can use the following:

find -type f -printf '%T@ %p\0'  | \
sort -zk1nr | \
sed -z 's/^[^ ]* //' | \
xargs -0 -I % echo % | \
while read f; do 
   mv "$f" "$(printf "%09d" $i).jpg"
   let i++

Note that this doesn't use ls for parsing, but uses the null byte as field separator in the different commands, respectively set as \0, -z, -0.

The find command prints the file time together with the name. Then the file are sorted and sed removes the timestamp. xargs is giving the filenames to the mv command through read.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download