【问题标题】:How to prevent automated overwriting of files , or how to add (1) and (2) to duplicate files instead of overwriting如何防止自动覆盖文件,或者如何将(1)和(2)添加到重复文件而不是覆盖
【发布时间】:2018-08-23 02:50:27
【问题描述】:

我创建了一个将在 FTP 服务器上运行的批处理文件。在 C:\images\0000 中,有一个相机可以保存 xxxxNG.txt 和 xxxxOK.txt 格式的文件。我编写的脚本用当前时间和日期重命名文件,并根据原始文件名将它们移动到其他地方的 OK 或 NG 文件夹。

这很好用,但是如果有多个图像要同时处理,程序将它们命名为相同的东西并覆盖直到不再有,只留下最后一个。

这是我目前所拥有的:

rem This is a simple script to move images from the FTP save location to the 
backup location (here)

echo off
cls
:again
@echo off
cls

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "dateandtime=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"

echo The current time is: %dateandtime%
echo.
echo Moving new files...

rem if exist %dateandtime%*.txt (


for /r "C:\test\Images" %%x in (*OK.txt) do move "%%x" C:\test\OK\" "%dateandtime%_OK.txt"

for /r "C:\test\Images" %%x in (*NG.txt) do move "%%x" C:\test\NG\" "%dateandtime%_NG.txt"

echo New files have been renamed and moved.
echo.
echo Checking for old files...

forfiles -p "C:\test\OK" -s -m *.* -d -1 -c "cmd /c del /Q @path"
forfiles -p "C:\test\NG" -s -m *.* -d -1 -c "cmd /c del /Q @path"

echo Files older than 5 years have been deleted.
echo.

timeout /t 1 /nobreak 

goto again

echo done

如何让它为同时处理的文件命名以不被覆盖并具有不同的名称?我尝试了一种检查文件是否已存在的方法,但我不确定如何修改 for /r "C:\test\Images" %%x in (*OK.txt) do move "%%x" C :\test\OK\" "%dateandtime%_OK.txt" 行来适应这个。我正在尝试类似

for /r "C:\test\Images" %%x in (*OK.txt) do move "%%x" C:\test\OK\" "%dateandtime%-%foo%_OK.txt"

但是 %foo% 打破了它。我以为我将 foo 理解为 for 循环的迭代。 do循环中是否有等价物?

提前谢谢你。

【问题讨论】:

  • 不是简单的解决方案是在重命名每个文件之前获取日期和时间,而不是只在脚本顶部获取一次吗?这样每个文件都会使用一个新的秒数。
  • 如上所述,有效地call将日期和时间创建为函数并使用延迟扩展来动态更新变量。 如果call 例程运行时间不到一秒,timeout 很容易用力
  • 或者更好的解决方案是使用原始文件名重命名文件,并在文件名末尾附加日期和时间。
  • 你在哪里见过说FOO 是循环中的FOR 命令迭代的文档。考虑到您使用的是%%x,这毫无意义。您在FOR 命令中定义的元变量是迭代。
  • 不知道,move接受三个参数...

标签: batch-file overwrite


【解决方案1】:

恕我直言,解决当前问题的最简单方法是使用原始文件名并将时间戳附加到原始文件名。

for /r "C:\test\Images" %%G in (*OK.txt) do move "%%G" "C:\test\OK\%%~nG-%dateandtime%%%~xG"

我对我的 FOR 元变量使用大写字母,这样它就不会对正在使用的命令修饰符造成任何混淆。

所以如果你的输入文件名是:

1234OK.txt
7890OK.txt

它们将被移动并重命名为:

1234OK-20180314104211.txt
7890OK-20180314104211.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2012-11-20
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多