循环批处理文件中存在隐藏文件不存在错误



我有一个批处理脚本,用于合并目录&子目录,这是我的代码:

@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 SubfolderEnigma

等等!

如果你做对了,你就不需要隐藏任何东西。

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

@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

最新更新