如果任何文件夹包含" Part"随地

时间:2014-07-17 16:17:54

标签: batch-file

感谢foxidrive Link to post

,我有这个脚本
@echo on
setlocal enabledelayedexpansion
set num=0
cd /d "C:\testfolder\test\test"  

if /i "%a:~-7%"=="Part" goto:process else goto:next

:process
for /f "delims=" %%a in ('dir /b /ad /o-d ') do (
set /a num+=1
set name=000!num!
set name=!name:~-3!
ren "%%a" "%%a - Part !name!"
)
pause

:next
pause 

之前

Folder 1

Folder 1 - Part 001

如果我再次执行脚本

Folder 1 - Part 001 - Part 001

解决方案

if /i "%a:~-7%"=="Part" goto:process else goto:next

我希望上面的代码能够找到workd" Part"。如果在任何地方找到它,它将GOTO:NEXT。我不知道我在这里失踪了什么,因为我尝试了它并没有用,我现在已经看了一段时间。谢谢你提前。

2 个答案:

答案 0 :(得分:1)

这个小批处理文件演示了如何在目录名称的任何位置识别字符串 Part 的子目录。

@echo off
setlocal enabledelayedexpansion
cd /d "C:\testfolder\test\test"

for /f "delims=" %%a in ('dir /b /ad /o-d ') do (
   set "DirName=%%a"
   if "!DirName:Part=!" == "!DirName!" (
      echo Directory "%%a" does not contain string "Part".
   ) else (
      echo Directory "%%a" contains string "Part".
   )
)
endlocal
echo.
pause

!DirName:Part=!根据环境变量 DirName 的值创建一个字符串,其中字符串 Part 被替换为空字符串。此字符串与环境变量 DirName 的未修改值进行比较。如果两个字符串相同,则目录名称不包含 Part

将2 echo命令替换为您的任务所需的任何内容。

第二个示例代码在目录C:\testfolder\test\test中搜索目录名中包含字符串 Part 的任何子目录,从最新到最旧的目录。循环在第一个子目录中立即退出,其中名称为 Part 。在这种情况下,环境变量 DirName 包含此子目录的名称。

@echo off
cls
setlocal enabledelayedexpansion
cd /d "C:\testfolder\test\test"

for /f "delims=" %%a in ('dir /b /ad /o-d ') do (
   set "DirName=%%a"
   if not "!DirName:Part=!" == "!DirName!" goto PartDirFound
)

DirName=
endlocal
echo No subdirectory contains "Part" in name.
echo.
pause
rem Exit this batch file as nothing do.
goto :EOF

:PartDirFound
rem Insert your code here instead of commands echo and pause.
echo "!DirName!" contains the string "Part" in name.
echo.
pause
DirName=
endlocal

但匹配更快的是具有相同执行行为的批处理:

@echo off
cd /d "C:\testfolder\test\test"

for /f "delims=" %%a in ('dir *part* /b /ad /o-d ') do (
   set "DirName=%%a"
   goto PartDirFound
)

cls
echo No subdirectory contains "Part" in name.
echo.
pause
rem Exit this batch file as nothing do.
goto :EOF

:PartDirFound
rem Insert your code here instead of commands echo and pause.
echo "%DirName%" contains the string "Part" in name.
echo.
pause
DirName=

答案 1 :(得分:0)

感谢Mofi的解决方案

@echo off
setlocal enabledelayedexpansion
set num=0

cd /d "C:\test\test"

for /f "delims=" %%a in ('dir *part* /b /ad /o-d ') do (
   set "DirName=%%a"
   goto PartDirFound
)

cls
for /f "delims=" %%a in ('dir /b /ad /o-d ') do (
set /a num+=1
set name=000!num!
set name=!name:~-3!
ren "%%a" "%%a - Part !name!"
)
pause
rem Exit this batch file as nothing do.
goto :EOF

:PartDirFound
rem Insert your code here instead of commands echo and pause.
echo "%DirName%" contains the string "Part" in name.
echo.
pause
DirName=