0

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 !

3
  • 1
    You have posted some code, told us what you want it to do, and not explained how it isn't doing what you require of it. As you appear to have unnecessarily used the set command, (effectively over coding), I've posted a quick example in the answer area, showing what I'd have expected your code to look more like. Commented Jun 23, 2020 at 12:50
  • What is the particular problem with your code? Commented Jun 23, 2020 at 13:15
  • I only have as a result for the folder name the element SAP thats why I don't understand Commented Jun 23, 2020 at 13:26

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response ! I dont know why it gave me this result : the folder name is correct but the after it gave me %B_%C... File found 20200614_SAP_ZCMF_MB51_V1.csv Folder name SAP_ZCMF_MB51 Folder %B_%C_%D exists Moving file 20200614_SAP_ZCMF_MB51_V1.csv to folder %B_%C_%D 1 file(s) moved. Finished```
@SaraATINE, apologies, I've edited the answer above, to include some missing parentheses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.