I tracked down this piece of code that does 50% of what I'm trying to do.
setlocal enabledelayedexpansion enableextensions
for /d %%f in (*) do (
set N=%%f
set N=!N:~0,-2!
ren "%%f" "!N!"
)
The folder structure I'm working with has 5 digit project numbers followed by a underscore and a revision letter. The code above removes the underscore and the revision letter and just leaves the project number as the name only. However when there is a project number with multiple revisions it just ignores them.
Folder name examples:
12000_A
10200_A
10200_B
10200_C
50000_A
Folder name result after running code.
12000
10200
10200_B
10200_C
50000
What I'd like to happen is all the files from the folders that have multiple revisions would be merged into 1 parent folder.
Expected result:
12000
10200 (folder contains A,B,C versions of the files)
50000
Is this possible? Thanks in advance
CodePudding user response:
The ren
command fails if the new file or directory name already exist, so you cannot use it to merge directories. The move
command is also not quite useful, because when you try to move a directory to an existing directory, it moves the whole source directory rather than its contents into the destination.
You could go for the xcopy
command to first copy and merge the source directories, together with the rd
command to eventually remove the successfully copied source directories then:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Iterate through all the directories in the current location:
for /D %%I in (".\*") do (
rem // Split off the first `_` and everything behind from the directory name:
for /F "delims=_ eol=_" %%J in ("%%~nxI") do (
rem // Copy the contents of the source directory into the new one:
xcopy /E /I /Y "%%~I" "%%~dpI%%J" && (
rem // Remove the source directory upon copying success:
ECHO rd /S /Q "%%~I"
)
)
)
endlocal
exit /B
After testing, remove the upper-case ECHO
command in order to actually remove directories.