Search code examples
batch-filerenamebatch-rename

Search file names from one list and replace them with another list in BATCH


I have two files :

old_names.txt
  oldname1
  oldname2 

new_names.txt 
  newname1
  newname2 

I would like to search my folder for file names containing "old_names" and replace "old_name" string with corresponding "new_name".

for /f %%i in (old_names.txt) do (

 // get corresponding %%j new_name

 for /f %%a in ('dir /b /a-d *%%i*') do ren %%a %%j

)

How can I retrieve the corresponding new_name ?


Solution

  • As per my comment. Create a single file called names.txt and add the strings you want to replace and what you want to replace it with:

    dummy replacement
    dummy2 replacement2
    

    then the script needs to be in the same directory, or you have to specify path to the files:

    @echo off
    setlocal enabledelayedexpansion
    for /f "tokens=1,2" %%i in (names.txt) do (
      for /f %%a in ('dir /b /a-d ^| findstr "%%i"') do (
        set "oldname=%%a"
        set "newname=!oldname:%%i=%%j!"
        echo ren "!oldname!" "!newname!"
      )
    )
    

    or by specifying path:

    @echo off
    setlocal enabledelayedexpansion
    for /f "tokens=1,2" %%i in (names.txt) do (
      for /f %%a in ('dir /b /a-d "D:\PATH" ^| findstr "%%i"') do (
        set "oldname=%%a"
        set "newname=!oldname:%%i=%%j!"
        echo ren "!oldname!" "!newname!"
      )
    )
    

    Once you are happy that it prints the files to replace to screen, simply remove the echo from the last line of code to actually perform the ren