批量复制唯一文件到新文件夹

时间:2017-03-24 01:22:49

标签: windows batch-file

关联的问题可能有助于查询的上下文:Get filename in batch for loop

我只是没有遵守替代规则,但我认为这是一个有类似答案的问题......

我正在使用以下批处理序列尝试相同类型的移动操作。有人能帮我纠正语法吗?

@echo off

set source=C:\Users\my name\some long path with spaces
set target=C:\Users\my name\a different long path with spaces

for %%F in ("%source%") do if not exist "%target%\%~nF.jpg" copy "%%F" "%target%\%~nF.jpg"

我们的想法是将所有没有扩展名的文件复制到具有匹配文件名的目的地,并且具有特定扩展名,并且具有正确的扩展名。在此先感谢任何人都能提供帮助!

编辑: 感谢参考Daniel,但我不是要尝试使用匹配的扩展名将文件名复制到目标位置。我正在尝试使用新扩展名将文件名复制到相同的文件名

示例:

source\filename001
destination\filename001.jpg
 - do nothing
source\filename002
destination\{no match}
 - copy source\filename002 to destination\filename002.jpg
亚历克斯,我不知道该怎么做。我在没有回声的情况下运行时看了输出,这就是我发布这个问题的原因。我不明白如何修改替换才能正常工作。

批处理输出错误:

for %%~F in ("%source%") do if not exist "%target%\%~nF.jpg" copy "%%F" "%target%\%~nF.jpg"
  

批处理参数中路径运算符的以下用法       替换无效:%~nF.jpg“copy”%% F“”%target%\%~nF.jpg“

for %%F in ("%source%") do if not exist "%target%\%~nF.jpg" copy "%%~F" "%target%\%~nF.jpg"
  

批处理参数中路径运算符的以下用法       替换无效:%~nF.jpg“copy”%% ~F“”%target%\%~nF.jpg“

解决方案:感谢您的帮助/解决方案/指导!

set "source=C:\Users\my name\some long path with spaces"
set "target=C:\Users\my name\a different long path with spaces"

for /F "delims=" %%F in (
  'Dir /B "%source%\*." '
) do if not exist "%target%\%%~nF.jpg" copy "%source%\%%~F" "%target%\%%~nF.jpg"

2 个答案:

答案 0 :(得分:1)

您的问题是,在批处理文件中,for可替换参数(变量,其中包含对正在迭代的元素的引用)需要前面有两个百分号({{1 }}),包括你使用任何修饰符的情况(例如文件名= %%F)。

在命令行中,可替换参数仅使用一个%%~nF,您的代码包括为批处理文件编写的一些引用,以及一些用于命令行的引用。

%

所以,解决它

for %%F in ("%source%") do 
    ^^^ for replaceable parameter in batch file, double %

if not exist "%target%\%~nF.jpg" copy "%%F" "%target%\%~nF.jpg"
                       ^^^^                           ^^^^
                       for replaceable parameters missing a % (usage in command line)

答案 1 :(得分:1)

MC ND有点快,但你必须在源代码中只选择没有扩展名的文件,所以我建议:

@echo off

set source=C:\Users\my name\some long path with spaces
set target=C:\Users\my name\a different long path with spaces

for /F "delims=" %%F in (
  'Dir /B "%source%\*." '
) do if not exist "%target%\%%~nF.jpg" copy "%%F" "%target%\%%~nF.jpg"
相关问题