BAT 文件从文件名中提取文件夹名称并将文件移动到该文件夹​​中

BAT 文件从文件名中提取文件夹名称并将文件移动到该文件夹​​中

我不太熟悉 Windows bat 文件编程,如果能得到任何帮助我将非常感激。

我需要一个 bat 文件来执行以下操作:

  • 从文件名中提取文件夹名称 - 例如,从文件名“123-Chemistry-101.rep”中提取化学。“-”可用于表示标记的开始和结束。
  • 将同一个文件移动到名为 Chemistry 的文件夹中。Chemistry 将成为所有报告所在的子目录。

我可能可以完成第二部分(我在这个网站上找到的),但第一部分超出了我的技能。

例如,对于 (*.rep) 中的 /RU:\Test %%f,请复制 %%f U:\test\Chemistry\

问候,杜兰德

答案1

您要求Batch,但我回答是Powershell因为我认为今天Batch对于这样的任务来说有点过时了,希望您的系统支持Powershell

$rootDir = "U:\Test"

$files = Get-ChildItem $rootDir -Filter *.rep

foreach($file in $files) {
  $folder = $file.toString().split("-")[1]
  $sourcefile = "$rootDir\$file"
  $targetdir = "$rootDir\$folder"
  if(!(Test-Path -Path $targetdir )){
    New-Item -ItemType directory -Path $targetdir
  }
  Move-Item $sourcefile $targetdir
}

编辑@Karan:

递归(保留子目录树):

$rootDir = "U:\Test"

$files = Get-ChildItem $rootDir -Filter *.rep -Recurse

foreach($file in $files) {
  $sourcefile = $file.Fullname
  $filepath = $file.PSParentPath
  $newfoldertocreate=$file.toString().split("-")[1]
  if(!(Test-Path -Path $filepath\$newfoldertocreate)){
    New-Item -ItemType directory -Path $filepath\$newfoldertocreate
  }
  Move-Item $sourcefile $filepath\$newfoldertocreate
}

答案2

从父文件夹运行此批处理文件报告文件夹

for /f "delims=" %%a in ('dir /b /s "Reports folder\*.rep"') do for /f "tokens=2 delims=-" %%i in ("%%~a") do (
    if not exist "%%~dpa%%i\" md "%%~dpa%%i"
    move "%%~a" "%%~dpa%%i\"
)

%%a 和 %%i 是两个中使用的变量为了循环。前者包含 .REP 文件的完整路径(由外循环提供),后者包含从文件名中提取的文件夹名称(由内循环提供)。

for /?是任何感兴趣的人都应该真正寻求更多帮助的地方(请注意,在批处理文件中,%符号是双倍的):

%~I  - expands %I removing any surrounding quotes (")
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only

那么“%%~dpa%%i”是什么意思呢?假设目录命令是"C:\Reports folder\123-Chemistry-101.rep"

%%~德巴意味着文件的驱动器号和路径减去周围的引号,即C:\Reports folder\

%%我正如我上面提到的,是从文件名中提取的文件夹名称(两个连字符分隔符之间的任何内容),因此在这种情况下Chemistry

综合起来,“%%~dpa%%i”将使该文件扩展为"C:\Reports folder\Chemistry",因为这是我们想要将文件移动到的位置。

相关内容