1

I have folders I upload files to, with 1,000-20,000 files of different kinds (pdf, jpg, wmv...etc) with different file names and lengths with spaces in the names, etc.

I am trying make a script to rename them on a regular basis, but I want them sorted by "oldest date first", and the new name will be in the format of YYYT000001.xxxx ... YYYY036242.xxxx (where YYYY is a fixed text "Jan" or Dec" (I will enter it manually in the script), and xxxx is the original file extension).

I've tried to use the input for i in $(ls -tr) as it will be sorted by oldest date, and tried to replace the file names using basename $i, etc.

I have searched the net but my thick head could not come up with a working script.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Lo Lo
  • 13
  • 2

1 Answers1

1

Using what they say in this question and this blog post, you just move the file like this:

#!/bin/bash
prefix="YYY"
i=0
for file in $(ls -tr)
do
    filename=$(basename "$file")
    extension="${filename##*.}"
    paddedIndex=$(printf "%06d" $i)
    mv $file ${prefix}${paddedIndex}.${extension}
    i=$(($i + 1))
done
Community
  • 1
  • 1
mgarciaisaia
  • 14,521
  • 8
  • 57
  • 81