BATCH Script - Create a folder with a specific part of the filename

自古美人都是妖i 提交于 2020-06-29 04:12:11

问题


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 !


回答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


来源:https://stackoverflow.com/questions/62532995/batch-script-create-a-folder-with-a-specific-part-of-the-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!