【问题标题】:Why I cannot copy with a variable name in windows batch file为什么我不能在 Windows 批处理文件中使用变量名进行复制
【发布时间】:2017-03-22 19:56:44
【问题描述】:

我有一个c:\test 目录,其中有一个文本文件var_list.txt,其中包含以下 3 行:

abc
xyz
def

我有一个C:\test\source 目录,其中有一个文本文件source_file.txt

我有一个空的C:\test\target 目录。

我想编写一个 Windows 批处理文件来执行这些任务:

  1. 在变量中逐行读取var_list.txt
  2. 对于每一行,将source_file.txtC:\test\source 目录复制到 C:\test\target 目录,其文件名也有变量行附加到它的名称中

所以当我运行这个 windows 批处理文件时,我希望它创建这 3 个文件:

  1. target_file_abc.txt
  2. target_file_xyz.txt
  3. target_file_def.txt

所以我在c:\test 目录中创建了一个Windows 批处理文件create_target_files.bat,其中包含以下内容:

@echo off
for /f "tokens=*" %%a in (var_list.txt) do (
  echo line=%%a
  copy /Y /V C:\test\source\source_file.txt C:\test\target\target_file_%a%.txt
)
pause

当我运行它时,我得到这个输出:

线=abc
已复制 1 个文件。
线=xyz
已复制 1 个文件。
线=定义
已复制 1 个文件。
按任意键继续。 . .

但在C:\test\target 目录中只创建了1 个文件target_file_.txt。为什么不使用变量名创建 3 个文件?

【问题讨论】:

    标签: windows batch-file cmd


    【解决方案1】:

    您的代码中有一个小错误。

    copy /Y /V C:\test\source\source_file.txt C:\test\target\target_file_%a%.txt
    

    在这行代码中,您使用的是%a% 而不是%%a

    由于您没有分配变量,%a% 会给您一个空白字符串。

    因此,所有复制的文件都被命名为target_file_.txt,它们会被最后一个文件覆盖。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      @echo off
      setlocal enabledelayedexpansion
      for /f "tokens=*" %%a in ('Type "C:\test\var_list.txt"') do (
          Set "line=%%a"
          echo !line!
          Copy /y /v "C:\test\source\source_file.txt" "C:\test\target\target_file_!line!.txt"
      )
      pause & exit
      

      有关如何以及何时使用Enabledelayedexpansion

      的更多信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2018-12-20
        • 2020-09-23
        • 1970-01-01
        • 1970-01-01
        • 2014-08-10
        • 2014-02-13
        相关资源
        最近更新 更多