如何根据名字将数千个文件移动到自己的文件夹中?

时间:2017-02-11 18:57:07

标签: batch-file command-line directory filenames

我正在制作一个BATCH文件,以便将数千个文件移动到一个名称基于名字第一个单词的新文件夹中。

示例:

c:\Monkeys likes apples.jpg
c:\Monkeys likes bananas.jpg
c:\Elephants likes avocados.jpg
c:\Elephants likes Grapefruit.jpg
-->
C:\Monkeys\Monkeys likes apples.jpg
C:\Monkeys\Monkeys likes bananas.jpg
C:\Elephants\Elephants likes avocados.jpg
C:\Elephants\Elephants likes Grapefruit.jpg

结果应显示一个名为' Monkeys'和大象'里面的文件。

这就是我所使用的,虽然这不是恰当地选择第一个单词。

@echo off
setlocal enabledelayedexpansion
set folderpath=G:\Emulator\GAMES\test\
for %%f in (%folderpath%\*.*) do (
  set "foldername=%%~nf"
  md "!foldername:~0,-3!" >nul 2>&1
  move "%%f" "!foldername:~0,-3!"
) 

提前感谢!

2 个答案:

答案 0 :(得分:2)

@echo off
setlocal enabledelayedexpansion
set "folderpath=G:\Emulator\GAMES\test\"
Pushd "%folderpath%"
For %%A in (*.jpg) do For /f %%B in ("%%~nA") Do (
  if not exist %%B md %%B  >nul 2>&1
  Echo move "%%~fA" %%B
  move "%%~fA" %%B
)
Popd

答案 1 :(得分:1)

这是另一种方法,它的表现如何?

@Echo Off
Set "folderpath=G:\Emulator\GAMES\test"

For %%A In ("%folderpath%\* *.*") Do Call :Sub "%%A"
Timeout -1
Exit/B

:Sub
    Set "newfolder=%~n1"
    Set "newfolder=%newfolder: ="&:%"
    If Not Exist "%~dp1%newfolder%\" MD "%~dp1%newfolder%"
    Move %1 "%~dp1%newfolder%"

以上代码专门针对包含至少一个空格的文件名,如果您希望包含每个文件,请在第4行将"%folderpath%\* *.*"更改为"%folderpath%\*.*"