Search code examples
batch-filedirectorymove

Batch File move files base on last characters of their name


Is it possible for a bat file to search for folders and files and
if it finds file named as part of a folder name to move that file into that folder.

For example:

D:\
└───Test
    │   161136.pdf
    │   23752.pdf
    │   24334.pd
    │
    ├───017-161136
    ├───021-23752
    ├───120-24334
    └───1560-4334

The name of the files are 4 to 6 characters and the folders are made to contain the files name.

Expected result

D:\
└───Test
    ├───017-161136
    │       161136.pdf
    │
    ├───021-23752
    │       23752.pdf
    │
    ├───120-24334
    │       24334.pdf
    │
    └───1560-4334

Solution

  • I don't see much difference using either PowerShell

    ## Q:\Test\2019\06\14\SO_56599031.ps1
    PushD D:\Test
    Get-ChildItem *-* -Directory | ForEach-Object {
        Move-Item ("{1}*" -f ($_.Name.split('-')[1])) -Dest $_.Name -WhatIf
    }
    PopD
    

    or batch to solve the task

    :: Q:\Test\2019\06\14\SO_56599031.cmd
    @Echo off
    Pushd D:\Test
    for /F "tokens=1* delims=-" %%A in ('Dir /B /AD *-*') do (
      move "%%~B*" "%%A-%%B"
    )
    PopD