【问题标题】:Windows Batch Static List Rename-MoveWindows 批处理静态列表重命名-移动
【发布时间】:2015-11-12 19:36:16
【问题描述】:

我对@9​​87654321@ 比较陌生,我正在尝试创建一个 Windows 批处理文件,该文件将一组中的静态数组值与另一组中的静态数组值重命名 - 移动到另一个文件夹。像这样的:

setlocal EnableDelayedExpansion

set currentDate=%date:~-4,4%%date:~-10,2%%date:~-7,2%
set fromPath=C:\
set toPath=C:\Temp\    

set fileList=(temp1.txt temp2.txt temp3.txt)
set toList=(name1 name2 name3)

我正在研究这种样式的数组,因为它看起来更容易让用户将其添加到列表中。

单独(没有 toList)fileList 工作正常:

for %%i in %fileList% do (
    IF EXIST %FromPath%%%i 
      ren %FromPath%%%i %%~ni_%currentDate%%%~xi & 
      move %FromPath%%%~ni_%currentDate%%%~xi %toPath%
)

但显然这不会按照与toList 中的列表相同的顺序从toList 重命名。

我尝试了带有这样索引的计数器的代码(也尝试了下面的其他变体)但没有运气:

for /L %%i IN (0,1,10) DO (
  IF EXIST %FromPath%%fileList[%%i]%
    ren %FromPath%%%i %%~ni_%currentDate%%%~xi & 
    move %FromPath%%%~ni_%currentDate%%%~xi %toPath%
)

这样的事情可能吗?如果没有,我愿意接受上述任何其他建议。

提前致谢!

【问题讨论】:

    标签: arrays windows file batch-file for-loop


    【解决方案1】:

    试试这个:

    @echo off
    setlocal EnableDelayedExpansion
    
    set currentDate=%date:~-4,4%%date:~-10,2%%date:~-7,2%
    set FromPath=C:\
    set toPath=C:\Temp\    
    
    set fileList=(temp1.txt temp2.txt temp3.txt)
    set toList=(name1 name2 name3)
    
    rem Separate toList elements into an array
    set i=0
    for %%a in %toList% do (
       set /A i+=1
       set "toList[!i!]=%%a"
    )
    
    set i=0
    for %%f in %fileList% do (
       set /A i+=1
       IF EXIST %FromPath%%%f (
          ren %FromPath%%%f %%~Nf_%currentDate%%%~Xf
          for %%i in (!i!) do move %FromPath%%%~Nf_%currentDate%%%~Xf %toPath%!toList[%%i]!
       )
    )
    

    有关批处理文件中的阵列管理的更多信息,请参阅:Arrays, linked lists and other data structures in cmd.exe (batch) script

    【讨论】:

    • '移动 C:\test1_20152108.txt C:\Temp\ !toList[1]!该命令的语法不正确。 '移动 C:\test2_20152108.txt C:\Temp\ !toList[2]!该命令的语法不正确。 echo 的输出是这样的... C:\>( set /A i+=1 IF EXIST C:\test1.txt ( ren C:\test1.txt test1_20152108.txt for %i in (!i!)移动 C:\test1_20152108.txt C:\Temp\ !toList[%i]! ) )
    • 您在原始代码的set toPath=C:\Temp\ 行中有错误的附加空格。最好以这种方式将值括在引号中:set "FromPath=C:\" - set "toPath=C:\Temp\" - 等等...
    • @tranceport:完成建议的修改后,我的解决方案是否有效?
    • no toList[%%i] 没有转换为数组中的值,即使设置行中有“”
    猜你喜欢
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2017-03-01
    • 2014-02-22
    相关资源
    最近更新 更多