【问题标题】:Compare the file names to create the folders they will be moved to比较文件名以创建它们将被移动到的文件夹
【发布时间】:2021-10-20 16:01:45
【问题描述】:

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

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

【问题讨论】:

  • 首先,/AD 将枚举目录,而您想枚举 PDF 文件。将其更改为/A-D,这意味着那些没有目录属性。然后,在您创建目录之前,您需要合并一些代码,这些代码根据返回为 %%I 的文件名确定您希望从中提取的子字符串作为您的目录名称。
  • 文件夹名称是否总是由两个相邻的单词组成?如果不是(如果文件名中的单词多于或少于 3 个),文件夹名称将由多少个单词组成?
  • 首先,mkdir %%I 应该是mkdir "%%I"。然后您必须准确指定如何从文件名中派生新目录的名称(它们是由前两个空格分隔的单词组成,还是由最后一个空格分隔的单词组成,或者是它背后还有其他逻辑吗?)...
  • 请不要破坏您自己的帖子。当您在此处发布时,即表示您授予 SO 在 CC-by SA 4.0 下分发内容的权利。任何破坏行为都将被撤销。
  • 你不能删除它,它有一个赞成的答案。

标签: windows batch-file cmd


【解决方案1】:

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

@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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多