首页 > 解决方案 > 比较文件名以创建它们将被移动到的文件夹

问题描述

我尝试根据它们的文件名创建文件夹并在它们各自的文件夹中移动文件。
例如,我有这些文件

daily planet today.pdf
daily planet tomorrow.pdf
the bridge fall.pdf
the bridge arise.pdf

我没有文件夹

我测试这个脚本

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "eol=| delims=" %%I in ('dir /AD /B /O-N 2^>nul') do (
  mkdir %%I
  if exist "%%I*.cbr" move /Y "%%I*.cbr" "%%I\"
)
endlocal

但它不会创建daily planetthe bridge文件夹。我期待这种情况,但它失败了(没有任何反应)

daily planet
     |
     +-- daily planet today.pdf
     +-- daily planet tomorrow.pdf


the bridge
     |
     +-- the bridge fall.pdf
     +-- the bridge arise.pdf

标签: windowsbatch-filecmd

解决方案


此方法假定文件夹名称由文件名中最后一个空格分隔的单词组成:

@echo off
setlocal EnableDelayedExpansion

for %%I in (*.pdf) do (

   set "file=%%I"
   for %%J in ("!file: =\!") do set "folder=!file: %%~nxJ=!"

   mkdir "!folder!" 2>NUL
   move /Y "!file!" "!folder!"
   echo "!file!" moved to "!folder!"

)

例如:

"the bridge fall.pdf" moved to "the bridge"
"the bridge arise.pdf" moved to "the bridge"
"bridge fall.pdf" moved to "bridge"
"bridge arise.pdf" moved to "bridge"
"the last bridge fall.pdf" moved to "the last bridge"
"the last bridge arise.pdf" moved to "the last bridge"

推荐阅读