Borut Kolar
Borut Kolar

Reputation: 23

Add sequential numbers to the beginning of the file names in folder

I have a lot of files in a folder and I want to add sequential numbers to the beginning of every file in this folder. I also want that files are ordered by their size, not in alphabetic order.

For example: file "something.mp3" should be renamed to "01 - something.mp3" if it's the biggest file in the folder. I want to do that on Windows.

Upvotes: 0

Views: 7530

Answers (4)

Steven K. Mariner
Steven K. Mariner

Reputation: 441

The FOR command can be used in a batch file to determine file size:

for %%F in (*.mp3) do echo [%%F] is [%%~zF] bytes

You'd have some work to do to get it to sort properly, though, since size 10 comes before size 2 in a text sort.

The DIR command can be used to list the files in size order:

dir /os *.mp3
dir /o-s *.mp3
dir /b /o-s *.mp3 > filesbysize.txt

Then you could use FOR /F to read that file and start doing your rename logic.

The SET /A command can be used to perform integer mathematics, so you could find a way to increment a counter in order to determine that prefix you want.

Be prepared to play around with each of these commands. The learning curve isn't bad, but it isn't zero.

Good luck!

Upvotes: 0

Anubis
Anubis

Reputation: 7435

ls -1S | awk '{print "mv \"" $0 "\" \""NR "_" $0"\";"}' | bash

However the parsing ls output is discouraged. Use this only if you know your filenames do not contain any abnormal characters. Read more here

Upvotes: 1

fzd
fzd

Reputation: 845

Since your OS might list files alphabetically, I recommend using printf at some point (This will generate "0001 - file1.mp3", "0002 - file2.mp3", etc.). To change the number of padding 0's, use another digit in printf %04d.

N=1  
while read -r file
do
  mv "$file" "$(printf %04d $N) - $file"
  N=$((N+1))
done < "$(ls -S)"

(or use "$(ls -rS)" if you want a reverse sort (biggest to smallest).

Upvotes: 0

daniu
daniu

Reputation: 15008

Bash:

I=0; for FILE in `ls -S`; do mv $FILE "$I - $FILE"; I=$((I+1)); done

Upvotes: 2

Related Questions