简体   繁体   English

无法使用批处理文件将文件移动到文件夹中

[英]Unable to move files into folders using batch files

i am trying to create folders using part of the file name (the first 10 digits unique digits) and then move the files to respective folders. 我正在尝试使用文件名的一部分(前10位唯一数字)创建文件夹,然后将文件移动到相应的文件夹。 I am able to create the folders but for some reason, unable to move the files into the folder. 我能够创建文件夹,但是由于某种原因,无法将文件移入文件夹。 Any idea why? 知道为什么吗? Here is my code: 这是我的代码:

@echo off
for /f %%a in ('dir /a-d /b') do (
  if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
)
goto :EOF
:func
set file=%~1
set dir=%file:~0,10%
md "%dir%" 2>nul
move "%file%" "%dir%" 
goto :EOF

It works, but not if your filenames have spaces in them, it will still create most or entire folder, depending on where the spaces are, but not move the file.. 它可以工作,但是如果文件名中没有空格,它仍然会创建大部分或整个文件夹,具体取决于空格在哪里,但不会移动文件。

So to rectify this try adding "delims=" to the for loop to skip default delimiters by default being whitespace. 因此,要解决此问题,请尝试在for循环中添加"delims=" ,以默认情况下跳过空白的分隔符。

@echo off
for /f "delims=" %%a in ('dir /a-d /b') do (
  if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
)
goto :EOF
:func
set file=%~1
set "dir=%file:~0,10%"
md %dir% 2>nul
move "%file%" "%dir%"

Although it seems odd, you can use RoboCopy to 'move' files too. 尽管看起来很奇怪,但是您也可以使用RoboCopy来“移动”文件。 The following example uses the Where command to select only files which contain at least 10 characters, (this means that you can keep your script name to less than 10 characters and you won't need to filter it) : 下面的示例使用Where命令选择仅包含至少10个字符的文件(这意味着您可以将脚本名的字符数保持在10个以内,并且不需要对其进行过滤)

@Echo Off
SetLocal EnableDelayedExpansion
For /F "Delims=" %%A In ('Where .:??????????*.*') Do (Set "FN=%%~nA"
    RoboCopy . "!FN:~,10!" "%%~nxA" /Mov>Nul)

Please bear in mind that this doesn't prevent directories being created which end with spaces, ie the 10th character of the filename is a space , which could cause you problems later! 请记住,这不会阻止创建以空格结尾的目录,即文件名的第10个字符是一个空格 ,以后可能会引起问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM