Search code examples
batch-filefile-rename

Remove specific number in file name


I am building out a batch file that may or may not have a 10 digit number within the filename. I would like to remove the first digit if it is a 10 digit number.

More specifically, the leading number may be a 1 in which case I want it removed.

Example filename: Softphone Test3_2020-12-08 15-23_13216549871.WAV

Desired output: Softphone Test3_2020-12-08 15-23_3216549871.WAV

In some cases there may only be a 9 digit number without the leading 1, this is okay and should stay the same way.

Please help me adjust this script to work appropriately:

for %%z in ("D:\Ipitomy\Recordings\%mm%-%dd%-%yyyy%\AT1*.WAV") do (
  for /f tokens^=4^,8^,10^,12^ delims^=^" %%a in ('type "D:\Ipitomy\Recordings\%mm%-%dd%-%yyyy%\index.xml"^|find /i "%%~nxz"') do (
    for /f "tokens=1,2 delims=:" %%t in ("%%b") do (
        ren "%z" "%c-%t-%%u_%d%~xz" 2>nul
        if errorlevel 1 set "Number=2" & call :NumberedRename "%%z" "%%c-%%t-%%u_%%d%%~xz"
    )
  )
)


Solution

  • I suggest this code for the task:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    for /F "delims=" %%I in ('%SystemRoot%\System32\where.exe "*_???????????.wav" 2^>nul') do (
        set "FullName=%%I"
        set "FileName=%%~nxI"
        setlocal EnableDelayedExpansion
        ren "!FullName!" "!FileName:~0,-15!!FileName:~-14!"
        endlocal
    )
    endlocal
    

    It processes only the WAV files with a ten digit number at end of the file name with renaming those files by removing the first digit from the ten digit number.

    To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

    • echo /?
    • endlocal /?
    • for /?
    • ren /?
    • set /?
    • setlocal /?
    • where /?

    Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded where command line with using a separate command process started in background with %ComSpec% /c and the command line within ' appended as additional arguments.