0

我需要一个批处理命令来查看目录的子文件夹并找到部分文件名。如果该文件存在,则移动该目录,否则不要理会它。

我有一个装满电影的文件夹:

D:\Movies\movie1\
         \movie2\
         \movie3\

在每个电影文件夹中,我想知道它是否有一个预告片下载到该文件夹​​中,如果有,那么将该目录移动到x:\movies. 我说的是部分文件名,因为每个预告片文件都将包含电影的标题,并-trailer在末尾添加“”(fe The Interview (2014)-trailer)。

4

1 回答 1

0

->让我们使用Windows CMD 命令行的 AZ 索引和下一个场景从 Windows CLI(命令行解释器)中寻找解决方案:

->tree d:\test\movies
D:\TEST\MOVIES
├───movie1
├───movie2
├───movie3
└───movie4

->tree d:\test\xmovies
D:\TEST\XMOVIES
No subfolders exist

->dir /B /S /A-D "d:\test\movies"
d:\test\movies\movie1\The View (2014)-trailer missing.rtf
d:\test\movies\movie2\The Interview (2014)-trailer.bat
d:\test\movies\movie2\The Interview (2014)-trailer.bmp
d:\test\movies\movie2\The Interview (2014)-trailer.txt
d:\test\movies\movie3\An Interview (2014)-trailer.bmp

要查找子文件MOVIES夹下的所有这些文件,并添加到文件扩展-trailer名前面的文件名末尾:.

->dir /B /S /A-D "d:\test\movies\*-trailer.*"
d:\test\movies\movie2\The Interview (2014)-trailer.bat
d:\test\movies\movie2\The Interview (2014)-trailer.bmp
d:\test\movies\movie2\The Interview (2014)-trailer.txt
d:\test\movies\movie3\An Interview (2014)-trailer.bmp

仅获取文件夹名称:

->for /F "tokens=*" %G in ('dir /B /S /A-D "d:\test\movies\*-trailer.*"') do @echo %~dpG
d:\test\Movies\movie2\
d:\test\Movies\movie2\
d:\test\Movies\movie2\
d:\test\Movies\movie3\

但这里movie2不止一次出现!而且,该move命令不允许带有尾随反斜杠的源目录:

->move "D:\test\Movies\movie4\" "D:\test\xMovies\"
The system cannot find the file specified.

->move "D:\test\Movies\movie4" "D:\test\xMovies\"
        1 dir(s) moved.

因此,我们需要从 Windows shell (CLI) 切换到批处理脚本。创建文件28167824.bat(例如,使用notepad并将其保存到D:\bat\StackOverflow文件夹):

@ECHO OFF >NUL
@SETLOCAL enableextensions disabledelayedexpansion
for /F "tokens=*" %%G in (
  'dir /B /S /A-D "d:\test\movies\*-trailer.*"'
  ) do (
    set "rawfolder=%%~dpG"
    if exist "%%~dpG" call :moveDir
  )
:endlocal
@ENDLOCAL
goto :eof

:moveDir
  set "srcfolder=%rawfolder:~0,-1%"
  `enter code here`echo move "%srcfolder%" "d:\test\xMovies\"
  rem move "%srcfolder%" "d:\test\xMovies\"
goto :eof

运行这个批处理脚本,下move一条命令的模板和上面提到的那个成功的move命令一样:

->D:\bat\StackOverflow\28167824
move "d:\test\Movies\movie2" "d:\test\xMovies\"
move "d:\test\Movies\movie2" "d:\test\xMovies\"
move "d:\test\Movies\movie2" "d:\test\xMovies\"
move "d:\test\Movies\movie3" "d:\test\xMovies\"

答对了!现在我们可以删除rembefore move "%srcfolder%" "d:\test\xMovies\",保存脚本并运行它:

->D:\bat\StackOverflow\28167824
move "d:\test\Movies\movie2" "d:\test\xMovies\"
        1 dir(s) moved.
move "d:\test\Movies\movie3" "d:\test\xMovies\"
        1 dir(s) moved.

这是最终配置,参见。起始场景:

->tree d:\test\movies
D:\TEST\MOVIES
└───movie1

->tree d:\test\xmovies
D:\TEST\XMOVIES
├───movie2
├───movie3
└───movie4
于 2015-01-28T17:26:27.670 回答