循环批处理文件

问题描述

我有一个批处理脚本,用于将目录和子目录中所有相同名称的txt文件合并为一个,这是我的代码

@echo off
for /f "tokens=*" %%a in (textfilenames.txt) do (
    for /D /R %%I in (%%a.txt) do (
    type "%%I" >> merged.tmp
    echo. >> merged.tmp
    )
    ren merged.tmp All_Combined_%%a.txt
  )
)
@pause

,因此当循环在某些目录下找不到文件时,将显示此消息:

The system cannot find the file specified. 
The system cannot find the file specified.
The system cannot find the file specified.
Press any key to continue . . .

我想隐藏上面的错误,所以我在文件名中使用了> NUL,例如:

@echo off
for /f "tokens=*" %%a in (textfilenames.txt) do (
    for /D /R %%I in ('%%a.txt^>NUL') do (
    type "%%I" >> merged.tmp
    echo. >> merged.tmp
    )
    ren merged.tmp All_Combined_%%a.txt
  )
)
@pause

但是我仍然收到错误消息,我想使此脚本完全无声,如无错误,或者如果某种不可能,那么我想将错误定制为:

The system cannot find the example.txt specified. in the \Subfolder\Enigma\

等等!

解决方法

如果操作正确,则无需隐藏任何内容。

在此示例中,我们将dir命令与/s函数一起使用来搜索文件。它不会抱怨找不到文件,因为它不希望文件在任何给定目录中无限期地存在,它只是搜索它:

@echo off
for /f "useback delims=" %%a in ("textfilenames.txt") do (
   for /f "delims=" %%I in ('dir /b/s/a-d "%%a.txt"') do (
    (type "%%I"
     echo()>>All_Combined_%%a.txt
    )
  )
)
@pause

请注意,由于不需要,我删除了ren部分。您可以在循环中写入合并的文件。

我也使用echo(代替echo.,原因可以在SO的众多答案中找到。

最后,我们可以通过将第二个for循环放在第一个内联代码中来消除一个带括号的代码块:

@echo off
for /f "useback delims=" %%a in ("textfilenames.txt") do for /f "delims=" %%I in ('dir /b/s/a-d "%%a.txt"') do (
    (type "%%I"
     echo()>>All_Combined_%%a.txt
  )
)
@pause