批处理脚本迭代形式

时间:2018-07-01 03:18:28

标签: windows batch-file batch-processing

我有一个批处理脚本:

  1. 检查目录中的文件,并检查其是否存在于另一个目录中 目录,并且该目录不应该存在
  2. 使用特定格式对每个文件计数,每个文件应该只有一个

如果以上两个陈述均成立,则生成成功文件。

下面是我的代码,它工作正常:

SET /A file1=file2=Val=0
SET /A FileE=1
set /a flagname=1

for %%A in (*ABC*.txt) do set /a file1+=1
for %%A in (*XYZ*.txt) do set /a file2+=1

for %%i in ("*") do if exist "Processed\%%~nxi" SET /A FileE=0

SET /A Val=%file1%*%file2%*%FileE% 

if %Val% EQU 1 (
echo SUCESS>Sucess.txt 
SET Flag=Sucess
echo %Flag%) else (

if %file1% EQU 0 ( echo Missing ABC.txt files >> Error.txt) 
if %file1% GTR 1 ( echo More than 1 ABC.txt files >> Error.txt) 

if %file2% EQU 0 ( echo Missing XYZ.txt files >> Error.txt) 
if %file2% GTR 1 ( echo More than 1 XYZ.txt files >> Error.txt)

(for %%i in ("*") do if exist "Processed\%%~nxi" echo(File Exists in 
Processed 
Folder %%~i)>>Error.txt
SET Flag=FAILURE
echo %Flag%) 

我的问题是如何转换上面的代码以遍历100个文件列表?以下是我尝试过的代码:

@echo off
setlocal enable delayed expansion
Set Filen[0]=ABC*.txt
Set Filen[1]=XYZ*.txt
SET /A Val=1 
SET /A File1=0

FOR /l %%G in (0,1,1) Do (
echo !Filen[%%G]! hi
set File1=0
echo %file1% Count
for %%A in (!Filen[%%G]! ) do (
set File1=!File1!+1
echo %%A %file1%)
)

1 个答案:

答案 0 :(得分:0)

将搜索词放入字符串中并对其进行迭代:

Set "Search=ABC DEF XYZ"
For %%A in (%Search%) do (

或者在一个文件中,一个一个地读取

For /f "usebackq" %%A in ("Search.txt") Do (

使用此文件Search.txt

ABC
DEF
XYZ

在环境中

> tree a:\ /F
Auflistung der Ordnerpfade für Volume RamDisk
A:\
└───Test
    │   ABC_123.txt
    │   DEF_456.txt
    │   Search.txt
    │
    └───Processed

以下批次

:: Q:\Test\2018\07\01\SO_51120147.cmd
@Echo off & Setlocal EnableDelayedExpansion
Set "BaseDir=A:\Test"
Set Err=^>^> "Error.txt" Call Echo=[%%date%% %%time%%] 
PushD "%BaseDir%" || (%Err% can't locate %BaseDir% & Pause &Goto :Eof)
%Err% Job %~f0 started by %USERNAME%
Set " Flag=Sucess"
:: Uncomment for string variant
:: Set "Search=ABC DEF XYZ"
:: For %%A in (%Search%) do (

:: use the file variant
For /f "usebackq" %%A in ("Search.txt") Do (
    Set Cnt=0
    For %%B in (%%A*.txt) Do Set /A Cnt=1
    if !Cnt! NEQ 1  (
      %Err% Count of %%A*.txt file=[!Cnt!]
      SET Flag=FAILURE
  )
)
For %%A in (*) do if exist "Processed\%%~nxA" (
    %Err% File %%A does exist in Processed Folder
  Set Flag=FAILURE
)
%Err% Job %~f0 terminated with %Flag%

提供此输出:

> type A:\Test\Error.txt
[2018-07-01 13:10:34,43]  Job Q:\Test\2018\07\01\SO_51120147.cmd started by LotPings
[2018-07-01 13:10:34,45]  Count of XYZ*.txt file=[0]
[2018-07-01 13:10:34,47]  Job Q:\Test\2018\07\01\SO_51120147.cmd terminated with FAILURE

编辑:有点棘手的行的解释:

Set Err=^>^> "Error.txt" Call Echo=[%%date%% %%time%%] 

不必在每行前/后添加错误行,
重定向和一个(固定的)文件名,我将它们与
echo命令和[date time]标记到变量中。

为避免在设置变量时立即解释,“>”必须 避免出现尖号,并延迟这些符号具有的%符号的扩展 要加倍。 (否则每个日志条目具有相同的日期时间)

在回显(伪)调用时必须强制扩展日期时间。