【问题标题】:Extract, check for duplicates and rename files in a sequential order from an archive in batch批量从存档中按顺序提取、检查重复文件和重命名文件
【发布时间】:2016-02-17 17:59:21
【问题描述】:

我一直在尝试以一种简单的方式实现通过 ftp 将图像文件复制到服务器。退出文件使用 P123456 结构,新文件应该在它们之后收到一个 _number,如 P123456_1。我没有设法让它们按顺序运行,但只能使用以下代码以随机模式运行。

set work=%temp%\%random%-%random%
mkdir "%work%"

set archives=*.rar

for %%A in (%archives%) do (
"%ProgramFiles(x86)%\7-Zip\7z.exe" e -o"%work%" "%%~A"
for %%F in ("%work%\*") do copy "%%~F" "%%~nF_%random%%%~xF"
)

rmdir "%work%"

如果新文件会为存档中的每个文件生成随机数,上述代码就足够了,但如果我在存档中有 P1、P2 和 P3,则批处理将输出 P1_random-number、P2_same-random-number、 P3_same-as-the-first-two “random” numbers 而不是 P1_random、P2-other-random 等。

【问题讨论】:

  • 在你的脚本中使用 setlocal DelayedExpansion 并使用 !random!而不是 %random% 使用该值

标签: batch-file random extract archive


【解决方案1】:

这是一个很好的例子来描述延迟扩展在批处理文件中的使用。

setlocal enabledelayedexpansion
set work=%temp%\!random!-!random!
mkdir "%work%"
set archives=*.rar

for %%A in (%archives%) do (
"%ProgramFiles(x86)%\7-Zip\7z.exe" e -o"%work%" "%%~A"
for %%F in ("%work%\*") do copy "%%~F" "%%~nF_!random!%%~xF"
 )
rmdir "%work%"

【讨论】:

    【解决方案2】:

    实现一个计数器很容易:

    setlocal enabledelayedexpansion
    set work=%temp%\%random%-%random%
    mkdir "%work%"
    set archives=*.rar
    set counter=0
    
    for %%A in (%archives%) do (
      REM you should delete the contents of %work% for each new archive:
      rmdir /q /s "%work%"
      mkdir "%work%"
      "%ProgramFiles(x86)%\7-Zip\7z.exe" e -o"%work%" "%%~A"
      for %%F in ("%work%\*") do (
        call :getfreename "%%~F"
        copy "%%~F" "%%~nF_!counter!%%~xF"      )
    )
    rmdir /q /s "%work%"
    goto :eof
    
    :getfreename
    set /a count+=1
    if exist "%~n1_%counter%%~x1" goto :getfreename
    goto :eof
    

    有关延迟扩展的简短演示,请参阅here

    【讨论】:

    • 两个答案都适用于首次运行,但只有 prudviraj 的版本适用于现有文件,Stephans 如果我运行脚本两次(或使用现有文件),脚本不会执行任何操作。尽管斯蒂芬的脚本更接近我想要的我猜它需要一个额外的文件是否存在添加+1?附:我不知道选择哪个答案是正确的,因为两者都以另一种方式正确:)。
    • 我添加了对现有文件的检查(请参阅我的编辑)我必须在for 循环之外进行,因为每个goto 都会破坏循环。如果你运行我的第一个版本两次,第二次运行又以Counter=0 开始。新版本应该涵盖(未经测试!)
    • 如果没有现有答案完全满足您的要求,您可以添加自己的答案并接受。
    猜你喜欢
    • 2014-04-22
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2018-04-26
    相关资源
    最近更新 更多