Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Batch file to move files to folders wher foldername is the same until underscore  (Read 3045 times)

0 Members and 1 Guest are viewing this topic.

buyt006

    Topic Starter


    Newbie

    Thanked: 1
    • Experience: Familiar
    • OS: Windows 7
    I want to move pdf-files to a folder where the foldername is the same as the filename until the _ in the filename.
    The batch has to look into the filename and compare all caracters before the first _ (underscore).
    If the caracters matches with a foldername move the file to that folder.
    If not, create a new folder with this name.

    Example filenames
    Mertens John_contract_3apr17.pdf
    Mertens Jake_contract_17apr17.pdf
    Van de Ven Peter_Contract_24apr17.pdf
    Van de Loo Ben_contract_28apr17.pdf

    Example foldernames
    Mertens John
    Mertens Jake
    Van de Ven Peter
    Van de Loo Ben

    I have no experience with batch-files and have found similar questions on the forum but no answer that works 100% for me.

    Hackoo



      Hopeful
    • Thanked: 42
    • Experience: Expert
    • OS: Windows 10
    Hi  ;)
    You can give a try for this batch file : just save it with your notepad editor with this name MovePDF2Folder.bat in the same location of your PDF files and execute it by double clic
    MovePDF2Folder.bat
    Code: [Select]
    @echo off
    @for %%f in (*.pdf) do (
    @for /f "delims=" %%a in ('echo %%f') do (
    @for /f "tokens=1 delims=_" %%b in ('echo %%a') do (
    If not exist "%%b" ( MD "%%b")
    move /Y "%%a" "%~dp0%%b"
    )
    )
    )
    pause & exit
    I found another approch on Stackoverflow posted by Mofi
    Code: [Select]
    @echo off
    for /F "tokens=1* delims=_" %%A in ('dir /B /ON *_*.pdf 2^>nul') do (
    md "%%A" 2>nul
            move /Y "%%A_%%B" "%%A"
    )
    pause
    « Last Edit: April 13, 2017, 06:51:11 PM by Hackoo »

    buyt006

      Topic Starter


      Newbie

      Thanked: 1
      • Experience: Familiar
      • OS: Windows 7
      Works perfect :)
      Thank you so much, Hackoo!!


      Hackoo



        Hopeful
      • Thanked: 42
      • Experience: Expert
      • OS: Windows 10
      Works perfect :)
      Thank you so much, Hackoo!!
      You are welcome dude  ;)  and don't forget to use the Thanks link  ;D
      Have a nice day  :)  8)