[英]Batch File - Find file and Replace
Basically I have created a batch file which copies a file within FOLDER A
and then renames the file with the date on the end and pastes it into FOLDER C
. 基本上,我已经创建了一个批处理文件,该文件将在FOLDER A
复制一个文件,然后使用末尾的日期重命名该文件并将其粘贴到FOLDER C
。
Before this takes place I am looking to find out how I would set up a FIND function to search through FOLDER B
to see if it has a file with the same name. 在进行此操作之前,我正在寻找如何设置FIND函数以搜索FOLDER B
以查看其是否具有相同名称的文件。
If it does contain the same name as the file in FOLDER A
then I want it to copy that file add the date on the end and paste it into FOLDER C
. 如果它确实包含与FOLDER A
中FOLDER A
相同的名称,那么我希望它复制该文件,并在末尾添加日期并将其粘贴到FOLDER C
。
Lets say: 可以说:
Hope this makes sense. 希望这是有道理的。
cmd has a builtin IF EXIST
that checks to see if a file exists, and the analagous IF NOT EXIST
. cmd具有一个内置的IF EXIST
,用于检查文件是否存在,以及类似的IF NOT EXIST
。 (See IF /?
or ss64.com ) Something like this would do what you describe. (请参阅IF /?
或ss64.com )类似您所做的事情。
IF NOT EXIST "%TARGET_FILE%" COPY "%SOURCE_FILE%" "%TARGET_FILE%"
cmd has some means of parsing paths, however, all the useful features are contained within the FOR
command (See FOR /?
or ss64.com ). cmd具有一些解析路径的方法,但是,所有有用的功能都包含在FOR
命令中(请参阅FOR /?
或ss64.com )。
I usually start with a typical environment variable, eg %SOURCE_FILE%
, give it to FOR
and allow FOR
's substitution behavior to get either the parent dir, filename, extension, etc. 我通常从一个典型的环境变量开始,例如%SOURCE_FILE%
,将其提供给FOR
并允许FOR
的替换行为获取父目录,文件名,扩展名等。
Suppose you wanted the base name of the file (no containing directory). 假设您想要文件的基本名称(不包含目录)。 You could accomplish that like this: 您可以这样完成:
FOR /F "tokens=*" %%f IN ("%SOURCE_FILE%") DO SET "SOURCE_FILE_BASE=%%~ff"
Now, SOURCE_FILE_BASE
would contain the base name of the file. 现在, SOURCE_FILE_BASE
将包含文件的基本名称。 (Note: the syntax of FOR
changes when you use it in a script vs at the interactive shell. The use of %%
is what a script needs.) (注意:在脚本中使用FOR
的语法与在交互式shell中使用时, FOR
的语法都会发生变化。脚本需要使用%%
。)
Based on what you describe, supposing you have a path to a file saved in SOURCE_FILE
and the directory where you wish to copy the file to, TARGET_DIR
, you could accomplish what you describe by doing something like: 根据您的描述,假设您具有保存在SOURCE_FILE
的文件的路径以及要将文件复制到的目录TARGET_DIR
,则可以通过执行以下操作来完成描述:
FOR /F "tokens=*" %%f IN ("%SOURCE_FILE%") DO SET "SOURCE_FILE_BASE=%%~ff"
SET "TARGET_FILE=%TARGET_DIR%\%SOURCE_FILE_BASE%"
IF NOT EXIST "%TARGET_FILE%" COPY "%SOURCE_FILE%" "%TARGET_FILE%"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.