最近我遇到了这个问题,我想要将许多文件从层次结构中移动到一个单独的文件夹中,但是它们有一样的文件名,我想要扁平化他们,但不想覆盖它们。我编写了一个脚本,将文件移动,但将旧的层次路径的名称加入到文件名中。例如:
源文件:
(保留HTML标签)
C:\files\somefiles\file.txt
C:\files\otherfiles\file.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"
renameandmovefilespart2.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%"