Klimashkin
Klimashkin

Reputation: 600

Remove file name prefix with cmd

I have thousands of files in one folder and most of them have prefix in name like this: NNNN_*.jpg

For example 3453_dfgdhfdgh.jpg, 1000_dfgdhfdgh.jpg, 5463_dfgdhfdgh.jpg etc.

How can I with CMD rename all files by remove prefix in files, in which such prefix exists?

Upvotes: 1

Views: 3318

Answers (1)

Joey
Joey

Reputation: 354516

If it is always a four-digit number in the front, then that's rather easy:

setlocal enabledelayedexpansion
for %%F in (*) do (
  set "FN=%%F"
  set "FN=!FN:~5!"
  ren "%%F" "!FN!"
)
goto :eof

But maybe you need to check first whether that's really true, in which case we need two helper functions (add them below the part above):

:IsDigit
set Digit=
if "%~1" GEQ "0" if "%~1" LEQ "9" set Digit=1
goto :eof

:IsNumber
setlocal
set "File=%~1"
set Number=
call :IsDigit "%File:~0,1%"
set Digit1=%Digit%
call :IsDigit "%File:~1,1%"
set Digit2=%Digit%
call :IsDigit "%File:~2,1%"
set Digit3=%Digit%
call :IsDigit "%File:~3,1%"
set Digit4=%Digit%
if "%Digit1%%Digit2%%Digit3%%Digit4%"=="1111" set Number=1
endlocal & set Number=%Number%
goto :eof

and then adapt as follows:

setlocal enabledelayedexpansion
for %%F in (*) do (
  set "FN=%%F"
  call :IsNumber "!FN!"
  if defined Number if "!FN:~4,1!"=="_" (
    set "FN=!FN:~5!"
    ren "%%F" "!FN!"
  )
)
goto :eof

Upvotes: 2

Related Questions