如果文件不存在则批量创建其他重命名

时间:2018-05-03 16:51:56

标签: batch-file cmd

if not defined filename set filename=123.txt
if not defined folder set folder=January
set BASE_DIR=C:\Users\xxx\Desktop\

set file=%BASE_DIR%%folder%\%filename%

我很难用算法来完成我想要做的事情。

每次此批处理脚本运行filename时,folder可能会有所不同。

  • 我正在尝试检查file exist是否不需要这样做 任何goto end
  • 如果文件 NOT 存在且该文件夹下有另一个文件。我需要用给定的更新文件名。

  • 但是,可能存在我甚至不存在文件夹的情况。 在这种情况下,我需要在该文件夹中创建文件夹和文件。

文件内的内容始终为空。

我不需要代码,我只需要逻辑帮助即可完成此任务。

1 个答案:

答案 0 :(得分:2)

这个评论的批处理文件应该有助于您完成批处理文件编码任务:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
if not defined FileName set "FileName=123.txt"
if not defined Folder set "Folder=January"

set "BASE_DIR=%UserProfile%\Desktop"
set "FilePath=%BASE_DIR%\%Folder%"
set "FullFileName=%FilePath%\%FileName%"

rem Exit batch file execution if file already exists.
if exist "%FullFileName%" goto :EOF

rem Create the entire directory structure for the file if directory
rem does not already exist. Note the backslash at end which prevents
rem condition evaluating to true if a file with name "%Folder%"
rem exists in "%BASE_DIR%".
if not exist "%FilePath%\" md "%FilePath%" 2>nul

rem The creation of the directory tree could fail for various reasons.
if not exist "%FilePath%\" (
    echo Error by %~f0:
    echo/
    echo Directory "%FilePath%" could not be created.
    echo/
    pause
    goto :EOF
)

rem Add here more code to create/copy/move file "%FileName%" in/to "%FilePath%".
rem For example creating an empty file:
type NUL >"%FullFileName%"

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • echo /?
  • endlocal /? ...此处未明确使用。 cmd.exe在终止批处理文件执行时自动恢复以前的环境。有关命令 SETLOCAL ENDLOCAL 的详细信息,请参阅this answer
  • goto /?
  • if /?
  • md /?
  • rem /?
  • set /?
  • setlocal /?
  • type /?

另见:

相关问题