bashrenamebatch-rename

Renaming files in a folder to sequential numbers


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).


Solution

  • 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, and using -- prevents mv from interpreting filenames with dashes as options.