Reputation: 23
I need help from you guys, I have been writing a script in Batch where I need to create a folder by using a part of the name of the file.
I need to have for example : for this file : 20200614_SAP_ZCMF_MB51_V1.csv I only need for the name of the folder SAP_ZCMF_MB51.
I need to delete the date and the version from the name of the folder.
Here is the code that allows me to create a folder :
@echo off
setlocal enabledelayedexpansion
for %%A in (*.csv) do (
echo file found %%A
for /f "delims=" %%B in ("%%A") do set fname=%%~nB
for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
for /f "tokens= 2,3 delims=_" %%D in ("!fname!") do set folname=%%D
echo folder name !folname!
if not exist "!folname!" (
echo Folder !folname! does not exist, creating
md "!folname!"
) else (
echo Folder !folname! exists
)
echo Moving file %%A to folder !folname!
move "%%A" "!folname!"
)
echo Finished
pause
Thanks in advance !
Upvotes: 0
Views: 217
Reputation: 38613
Here is a quick rewrite of your posted code, without the unnecessary set commands, and using the appropriate tokens and delimiters for the file name pattern you've provided.
@Echo Off
SetLocal EnableExtensions
For %%A In (????????_*_*_*_*.csv) Do (
Echo File found %%A
For /F "Tokens=2-4 Delims=_" %%B In ("%%~nA") Do (
Echo Folder name %%B_%%C_%%D"
If Not Exist "%%B_%%C_%%D\" (
Echo Folder %%B_%%C_%%D does not exist, creating
MD "%%B_%%C_%%D"
) Else Echo Folder %%B_%%C_%%D exists
Echo Moving file %%A to folder %%B_%%C_%%D
Move /Y "%%A" "%%B_%%C_%%D"
)
)
Echo Finished
Pause
Upvotes: 1