Search code examples
batch-filebatch-rename

How to rename lines of files according to text in different file?


I have multiple files like test1.html, test2.html ... testn.html and so on and in the same folder i have names.txt with all names for that test{n}.html files. How can i loop through names.txt file and according to lines from it rename all html files?

names.txt structure like:

randomName 
NameRandom 
test 
Name
...

Solution

  • You will want to use a combination of FOR and SET /a to get this done. You would essentially increment a counter with SET /a inside a FOR loop that read the names.txt file, renaming the files based on the counter value and line entry.

    setlocal enableDelayedExpansion
    SET counter=0
    FOR /F "usebackq tokens=* delims=" %%f IN (names.txt) DO (
      SET /a counter=!counter!+1
      ECHO.N:!counter!
      REN "test!counter!.html" "%%f.html"
    )
    

    To perform variable manipulation within a loop you also need Delayed Expansion enabled (setlocal enableDelayedExpansion).