전준휘
전준휘

Reputation: 115

Is there a command that can be moved to a folder by file name in Windows?

I want to read the file name with the command and automatically move it to the folder with the same name. What should I do?

example:

before processing

enter image description here

after processing

enter image description here

If I have files and folders with the same name, I want to move them to a folder with the same name.

What should I do? Do I have a cmd command?

Upvotes: 0

Views: 102

Answers (2)

Hackoo
Hackoo

Reputation: 18827

Here is another approach using regex in vbscript with a batch file :

@echo off & color 0A
Title Extract Title using Regex in vbscript

SetLocal EnableDelayedExpansion
@for /f "delims=" %%a in ('dir /b *.xlsx') do (
    Call :Extract_Title "%%a" Title
    If Defined Title (
        If Not Exist "!Title!\" MkDir "!Title!\"
        Move /-Y "%%a" "!Title!\"
    )
)

Pause & Exit
::----------------------------------------------------------------------------------------
:Extract_Title <InputFile> <Title to be Set>
>"%tmp%\%~n0.vbs" (
    echo WScript.StdOut.WriteLine Extract_Title(Data^)
    echo Function Extract_Title(Data^)
    echo    Data = Wscript.Arguments(0^) 
    echo    Set re = New RegExp 
    echo    re.Global = True 
    echo    re.IgnoreCase = True  
    echo    re.Pattern = "(\S+|\S.+)_" 
    echo    For Each Match in re.Execute(Data^) 
    echo        Title = Match.SubMatches(0^) 
    echo    Next
    echo    Extract_Title = Title
    echo End Function
)
@for /f "delims=" %%A in ('cscript /nologo "%tmp%\%~n0.vbs" "%~1"') do set "%2=%%A"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::----------------------------------------------------------------------------------------

Upvotes: 2

AppetiteForDestruction
AppetiteForDestruction

Reputation: 174

I will provide both a solution to this exact question, and an alternative that I would suggest to handle this situation.

==========
~ Solution ~
==========

  • Copy/Paste the code below into an empty file, save, and execute.
@echo off

for /f "tokens=1,* delims=_" %%a in ('dir /b *.xlsx') do (
  if not "%%a_%%b"=="%~nx0" (
    if not exist %%a mkdir %%a
    move "%%a_%%b" "%%a\"
  )
)
  • You can change the "*.xlsx" to any other file extension, or change to "*.*" to work with ANY file extension.
  • Keep in mind though, this ONLY works with filenames that are formatted like the way you mentioned in your question.

===================
~ Alternative Solution~
===================

I would suggest the Shell Extension "Files 2 Folder" as an alternative. I came across a situation where I needed something similar to what you're asking a couple years ago, and this ended up working out great.

https://www.dcmembers.com/skwire/download/files-2-folder/

screenshot

Upvotes: 4

Related Questions