Search code examples
windowsbatch-filecmdmovefindstr

Find in file then move the file


I have an unknown number of text files in a directory which are named as such, ABC1200f1234.EAU, but they are all slightly different. The internal structure of each text file is the same, but the contents are different. Within each file there is a string * SERIAL NUMBER:XXXXX *. For each file the 6 characters following the SERIAL NUMBER: is different. I am trying to search each file to obtain the 6 digits following SERIAL NUMBER: then move that file to a directory named after the 6 digits, e.g. if the 6 digits are A12345 then I want to create a directory named A12345 and move the file there, then move on to the next file until all files have been moved.

The following code gets the 6 digits into %%a but I'm stuck on how to then move the file, before moving onto the next one. I'm sure I'm just missing one small piece of the puzzle.

@ECHO OFF
CLS
cd c\Temp

setlocal enableextensions disabledelayedexpansions
set sourcedir=c:temp
set targetdir=c:\temp\parsed

for /f "tokens=4 delims=*:" %%a in (
    'findstr /r "SERIAL NUMBER:" %sourcedir%\*'
) do (
    if exists %targetdir%\%%a (
        echo Directory already exists
    ) else mkdir %targerdir%\%%a
)
move %sourcedir%\%%a %targetdir%\%%a
)

I'm sure the last line is the problem because %%a now holds the 6 digit number, not the filename.

Please don't suggest Powershell as that is not an option. I also realise I can use robocopy and remove the check to see if the target directory exists.

Any help you can give would be most appreciated.


Solution

  • I'm assuming for this code that the serial number is directly after the colon with no white space or other characters whcih need to be removed before or after it.

    @(setlocal EnableDelayedExpansion
      ECHO OFF
      CLS
      set "sourcedir=c:\temp"
      set "targetdir=c:\temp\parsed"
      SET "FileGlob=*.EAU"
    )
    
    CALL :Main
    
    ( Endlocal
      EXIT /B
    )
    
    :Main
      FOR %%_ IN (
        "%sourcedir%\%FileGlob%"
      ) DO (
        Echo=processing "%%~_"
        FOR /F "Tokens=2 delims=:" %%F IN ('
          TYPE "%%~_" ^| FIND /I "SERIAL NUMBER:"
        ') DO (
          ECHO=Found. Serial number "%%F" trimmingbany spaces
          FOR /F "Tokens=*" %%f IN ("%%~F") DO (
            ECHO=Trimmed serial number "%%~f" stored
            SET "_TmpFolder=%%F"
          )
        )
        MD "%TargetDir%\!_TmpFolder!\"
        MOVE "%%~_" "%TargetDir%\!_TmpFolder!\%%~nx_"
      )
    GOTO :EOF