I have a set of files I wish to copy to a new set of subfolders.
For instance:
0_107_206.tif
1_0_69.tif
1_16_75.tif
1_40_117.tif
2_0_36.tif
2_26_62.tif
35_0_19.tif
These files are stored in folders based on the first substring of the filename such as 0, 1 or 35. I want to create subfolders based on the second substring between the 2 '_' characters. I have tried several things along the lines of
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%B in (*.tif) DO (
SET FileName=%%B
SET FileName1=!FileName:~2!
SET FileName2=!FileName1:~0,-7!
MD %TargetPath%!FileName2!
)
ENDLOCAL
But this is not flexible enough. Is there a way to get the position of the '_' characters and feed that into a SUBSTRING function? Naturally this needs to work in a loop since there are thousands of files I need to proces.
Thanks in advance.
FOR %%B in (*.tif) DO (
for /f "tokens=1,2 delims=_" %%x in ("%%~B") do (
md "%TargetPath%%%~y"
copy %%~B "%TargetPath%%%~y\%%~B"
)
)
?
Given a file structure
u:\0\0_107_206.tif
u:\1\1_0_69.tif
u:\1\1_16_75.tif
u:\1\1_40_117.tif
u:\2\2_0_36.tif
u:\2\2_26_62.tif
u:\35\35_0_19.tif
Then this batch:
@ECHO OFF
SETLOCAL
SET "sourcedir=u:"
SET "destdir=c:\destdir"
FOR /f "tokens=1*delims=" %%a IN (
'dir /s /b /a-d "%sourcedir%\*_*_*.tif" '
) DO FOR /f "tokens=1,2,3delims=_" %%B IN ("%%~na") DO (
ECHO MD "%destdir%\%%C"
ECHO COPY /b "%%a" "%destdir%\%%C\"
)
GOTO :EOF
would generate
MD "c:\destdir\107"
COPY /b "u:\0\0_107_206.tif" "c:\destdir\107\"
MD "c:\destdir\0"
COPY /b "u:\1\1_0_69.tif" "c:\destdir\0\"
MD "c:\destdir\16"
COPY /b "u:\1\1_16_75.tif" "c:\destdir\16\"
MD "c:\destdir\40"
COPY /b "u:\1\1_40_117.tif" "c:\destdir\40\"
MD "c:\destdir\0"
COPY /b "u:\2\2_0_36.tif" "c:\destdir\0\"
MD "c:\destdir\26"
COPY /b "u:\2\2_26_62.tif" "c:\destdir\26\"
MD "c:\destdir\0"
COPY /b "u:\35\35_0_19.tif" "c:\destdir\0\"
So you'd just need to change source and destination directory names to suit; change the copy
command to move
if appropriate; remove the ECHO
keywords to activate.
You could also append 2>nul
to the MD
line to suppress the 'diretory already exists' message.
OR, you could replace the COPY
with XCOPY
and then the MD
would become irrelevant.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.