我最近不得不解决这个问题,并且我想从层次结构移动到单个文件夹的许多文件彼此具有相同的名称,并且我仍然希望在不覆盖它们的情况下使层次结构变平。我所做的是编写一个移动文件的脚本,但使用名称中的旧层次结构路径重命名它,
例如:源文件:
C:\files\somefiles\file.txt
C:\文件\其他文件\文件.txt
目标是 C:\newdir\ 文件创建为
C:\newdir\somefiles-file.txt
C:\newdir\otherfiles-file.txt
这是代码,批处理文件 1 遍历文件,批处理文件 2 重命名并移动它们(如果您想保留源代码,也可以复制:
@echo off
for /r %%f in (*.*pr) do @renameandmovefilespart2.bat "%%f" "%%~ff" "%%~xf"
重命名和移动文件part2.bat
@echo off
Setlocal EnableDelayedExpansion
rem set the whole file path
set origWhole=%1
set origPathOnly=%2
set extension=%3
rem here you can set where the directory to hold the flattened hierarchy is
set destDir=c:\destinationDir\
rem set the directory to do a string replace
rem make this the starting directory, that you dont want in the newly renamed files
set startingDir=C:\starting\directory\
set nothing=
set slash=\
rem here you can set what the character to represent the directory indicator \ in the new files
set reaplcementDirectoryCharacter=--
set quote="
rem cut out the starting part of the directory
call set newname=%%origWhole:!startingDir!=!nothing!%%
rem replace slashes with new character
call set newname=%%newname:!slash!=!reaplcementDirectoryCharacter!%%
rem remove quotes
call set newname=%%newname:!quote!=!nothing!%%
rem @echo shortened: %newname%
rem @echo source path: %origPathOnly% newPath: %startingDir%
rem @echo extension: %extension%
rem rename the files
ren %origWhole% %newname%
rem prepare to move the file, clean up the source path
call set origPathOnly=%%origPathOnly:!quote!=!nothing!%%
move "%origPathOnly%%newname%" "%destDir%"