Search code examples
windowsbatch-filecmd

Creating dir according to part of filename


I'm looking to archive 10.0000+ files in a similar format:

files:

  • 871-517-06461-1-120-01.pdf
  • 871-517-06461-1-113-01.stp
  • 871-517-06461-1-100-01.pdf

Example dir generated: 871-517-06461-1

  • NAV
  • TPD <- (files need to moved here)
  • INS

files:

  • 871-517-21541-1-100-01.pdf
  • 871-517-21541-1-110-01.pdf
  • 871-517-21541-1-113-01.stp

Example dir generated: 871-517-21541-1

  • NAV
  • TPD <- (files need to moved here)
  • INS

What would be the way to archieve this? I came up with this:

@echo off
setlocal enabledelayedexpansion
for %%A in (*.pdf *.stp) do (
   set data=%%A
   echo file found !data:~0,16!
   for /f "delims=" %%B in ("%%A") do set fname=%%~nB
   for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
   for /f "tokens=1* delims=_" %%D in ("!fname!") do set folname=%%D
   echo folder name !folname:~0,16!
   if not exist "!folname:~0,16!" (
      echo Folder !folname:~0,16! does not exist, creating
      md "!folname:~0,16!"
      md "!folname:~0,16!\TPD"
      md "!folname:~0,16!\NAV"
      md "!folname:~0,16!\INS"
   ) else (
      echo Folder!folname:~0,16! already exists >> log.txt
   )
   echo Moving file %%A to folder !folname:~0,16!
   move "%%A" "!folname:~0,16!\TPD"
   )
echo Finished
pause

It's working, but how can i simplify this? Also can i somehow change the character count with setting a variable? Is it possible to remove the last - sign? So 871-517-06461-1 is named 871-517-064611.


Solution

  • Does this help you out?

    It doesn't count characters, (yours should have been 15 anyway), it isolates everything up to the fourth hyphen/dash, -.

    @Echo Off
    SetLocal EnableExtensions
    For /F "Delims=" %%G In (
        '(Set PATHEXT^=^) ^& %SystemRoot%\System32\where.exe "%~dp0.":"?*-?*-?*-?*-*.pdf" "%~dp0.":"?*-?*-?*-?*-*.stp" 2^>NUL'
    ) Do For /F "Tokens=1-4,* Delims=-" %%H In ("%%~nG") Do (
        For %%L In (INS NAV TPD) Do If Not Exist "%%~dpG%%H-%%I-%%J-%%K\%%L\" MD "%%~dpG%%H-%%I-%%J-%%K\%%L"
        If Exist "%%~dpG%%H-%%I-%%J-%%K\TPD\" Move /Y "%%G" "%%~dpG%%H-%%I-%%J-%%K\TPD" 1>NUL
    ) 
    

    I haven't included all of the pointless echoing of messages, so you'll need to adapt it for those if you really need them. Please however, do not make such changes before you've tested it. The only thing you may need to change is the source path; the above uses %~dp0. for the same location as the running batch file, you could change that to just ., for the current directory, or an actual relative or absolute path, if you prefer, (taking care not to remove their enclosing double-quotes).