Ismail AMANI
Ismail AMANI

Reputation: 15

rename all files sequentially with same extension using batch file

I wanna rename this files like that:

File 1.pdf  > 1.pdf
File 2.pdf  > 2.pdf
..
File 10.pdf >10.pdf
File 11.pdf >11.pdf
File1 1.pdf >12.pdf      
File1 2.pdf >13.pdf
..

This code it's working but not Sorting Them:

    @echo off & setlocal EnableDelayedExpansion 

set a=1
for /f "delims=" %%i in ('dir /b *.pdf') do (
  ren "%%i" "!a!.pdf" 
  set /a a+=1
) 

The result is :

File 1.pdf  > 1.pdf
File 10.pdf > 2.pdf
File 11.pdf > 3.pdf

Upvotes: 1

Views: 95

Answers (2)

michael_heath
michael_heath

Reputation: 5372

@echo off
setlocal enabledelayedexpansion

if "%~1" == "stage1" goto :stage1
if "%~1" == "stage2" goto :stage2
if not "%~1" == "" exit /b 1

cmd /c "%~f0" stage1 | sort | cmd /c "%~f0" stage2
exit /b 0

:stage1
for /f "delims=" %%A in ('dir /b *.pdf') do (
    for /f "tokens=1,*" %%B in ("%%~nA") do (
        set "token1=%%~B                             "
        set "token2=                             %%~C"
        echo "!token1:~0,20!"^|"!token2:~-20!"^|"%%~A"
    )
)
exit /b 0

:stage2
set i=0
for /f "delims=" %%A in ('more') do (
    set /a "i+=1"
    for /f "tokens=3 delims=|" %%B in ("%%~A") do (
        echo ren "%%~B" "!i!.pdf"
    )
)
exit /b 0

Label stage1 pads the 2 tokens of the filename with spaces and then trims each to 20 characters in length. Each line is echoed with "token1 padded"|"token2 padded"|"full filename", which is piped to sort, and then piped to label stage2 for indexing and renaming.

Remove the echo in front of the ren command if test is good.

Output:

ren "File 1.pdf" "1.pdf"
ren "File 2.pdf" "2.pdf"
ren "File 10.pdf" "3.pdf"
ren "File 11.pdf" "4.pdf"
ren "File1 1.pdf" "5.pdf"
ren "File1 2.pdf" "6.pdf"

Upvotes: 1

philselmer
philselmer

Reputation: 751

You can test a to see if it is less than 10 and add a zero to the filename like this:

if !a! LSS 10 ren "%%i" "0!a!.pdf" else ren "%%i" "!a!.pdf"

If you have more than 100 file to rename, you can make it like this:

if !a! LSS 10 set newfile="00!a!" else if !a! LSS 100 set newfile="0!a!"

ren "%%i" "!newfile!.pdf"

Putting it all together, this worked for me:

@echo off & setlocal EnableDelayedExpansion 

set a=1
for /f "delims=" %%i in ('dir /b *.pdf') do (
  set newfile="!a!"
  if !a! LSS 1000 set newfile="0!a!"
  if !a! LSS 100 set newfile="00!a!"
  if !a! LSS 10 set newfile="000!a!"

  ren "%%i" "!newfile!.pdf"
  set /a a+=1
)

Upvotes: 0

Related Questions