Search code examples
searchbatch-filefilenamesmove

Batch file to: move files into a sub folder if they contain the filename of another file


This code works well for me to move files with the same filename but different extension into a subfolder.

So the current logic is: If an NC1 file has the same filename as a PDF file then move that NC1 to its respective subfolder.

But my files don't have the same filename.

The following are 2 example files:

  • "f100.nc1"
  • "999-P-f100 - PLATE - Rev 0 - 287x200.pdf"

How do I change this code to follow this logic: If a PDF filename CONTAINS the filename of an NC1 file then move that NC1 to its respective subfolder.

    for %%j in ("..\2PDF_Outsourced\1PDF_Heavy\*.pdf") do (
        if exist "%%~nj.nc1" (
            move /-y "%%~nj.nc1" "\2NC1_Outsourced\1NC1_Heavy"
        )
    )

    for %%j in ("..\2PDF_Outsourced\1PDF_Light\*.pdf") do (
        if exist "%%~nj.nc1" (
            move /-y "%%~nj.nc1" "\2NC1_Outsourced\1NC1_Light"
        )
    )

Thank you in advance for any help. I have been stuck at this stage for a while and am struggling to understand delimiters, strings, and wildcards.


Solution

  • The trick is to reverse your logic. Iterate the .nc1 files and then look to see if matching .pdf exists (with wildcards). Adding a 2nd loop for Heavy and Light avoids code replication.

    for %%F in ("*.nc1") do for %%P in (Heavy Light) do (
      if exist "..\2PDF_Outsourced\1PDF_%%P\*%%~nF*.pdf" (
        if exist "%%F" move /-y "%%F" "\2NC1_Outsourced\1NC1_%%P"
      )
    )
    


    EDIT

    I added a 2nd IF EXIST to the code above just in case the name matches both Heavy and Light pdf files.

    If Endoro's concern about ignoring names that match a substring of a larger word is valid, then the above can be extended:

    for %%F in ("*.nc1") do (
      set "name=%%~nF"
      setlocal enableDelayedExpansion
      for %%C in (. [ ^^) do set "name=!name:%%C=\%%C!"
      for %%N in (!name!) do (
        endlocal
        for %%P in (Heavy Light) do for /f "eol=: delims=" %%A in (
          'dir /b /a-d "..\2PDF_Outsourced\1PDF_%%P\*%%~nF*.pdf"^|findsdr /i "\<%%N\>"'
        ) do if exist "%%F" move /-y "%%F" "\2NC1_Outsourced\1NC1_%%P"
      )
    )