Home > Enterprise >  How to rename folders based on text file where names are not in the same order
How to rename folders based on text file where names are not in the same order

Time:09-06

I have the following code that works, but I still need more functionality.

@echo off
setlocal EnableDelayedExpansion

< albumsids.txt (
   for /F "delims=" %%a in ('dir /B *.*') do (
      set /P newalbumsids=
      ren "%%~Fa" "!newalbumsids!%%~Xa"
   )
)

I have several folders like:

Folder
Folder name 1
Folder name 2
Folder name 3
Folder name 4
Folder name 5
Folder name 6

and an .txt file with the name I wish to rename my folders: The .txt file I fill manually the new names

albumsids.txt

6544233_Folder
1234233_Folder_name_1
6575670_Folder_name_2
4756722_Folder_name_3
3375673_Folder_name_4
6575675_Folder_name_5
8575677_Folder_name_6
the list continue..

My problem is that not all the time in .txt the names are in order and I have hundreds of folders. Most of the time are mixed:

albumsids.txt

1234233_Folder_name_5
6575670_Folder_name_3
6544233_Folder
475672_Folder_name_6
3375673_Folder_name_2
6575675_Folder_name_1
8575677_Folder_name_3
the list continue..

I need it to load the entire text file, search in .txt for the partial name of the initial folder Folder name and then copy the entire title with which to rename the folder that match.

Basically the new names insterted manually by me contain an "unique ID" and "_" used as delimiter all the time the structure will be:

Uniqueid_FOLDER_NAME
Uniqueid_FOLDER

Folder can be from 1 word or more, so

Folder  will become 1234233_Folder
Folder Name 5  will become 1234233_Folder_name_5
Folder Name 1  will become 1234233_Folder_name_1
Folder Name 3  will become 1234233_Folder_name_3
and so on...

thank you for helping me

CodePudding user response:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory and filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q73613649.txt"

FOR /f "usebackqtokens=1*delims=_" %%b IN ("%filename1%") DO (
 SET "#=%%c"
 SET "#=!#:_= !"
 ECHO REN "%sourcedir%\!#!" "%%b_%%c"
)
GOTO :EOF

Always verify against a test directory before applying to real data.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.

Simply, split the new name into 2 parts using _ as a delimiter, replace the underscores from the second part with spaces, then rename the directory. If the directory may not exist, either bear with the error message or dump it by appending 2>nul to the ren line.

  • Related