2011-08-17 101 views
2

我正在編寫一個批處理文件,該文件解析文本文件並僅在讀取該文件中的特定行時才生成輸出。考慮命名下面的文本文件sample.txt在批處理文件中使用變量作爲標誌

List1 
Dog 
Cat 
Monkey 

List2 
Horse 
Bear 
Dog 
Pig 
Dog 

比方說,我的批處理文件的目的是爲了輸出單詞「狗」多少次出現在每個列表。因此,在sample.txt的有兩個列表:一個有「狗」的1個實例,而另一個具有2.要在批處理文件中實現這一點,我寫了下面:

@echo off 
set count=0 
set first_iteration=1 

for /f "tokens=*" %%A in (sample.txt) do (
    echo %%A > tempfile.txt 

    FINDSTR /R ".*List.*" tempfile.txt > NUL 

    REM If true, this is a list header 
    if errorlevel 1 (
     if %first_iteration% EQU 1 (
      REM PROBLEM HAPPENS HERE 
      set first_iteration=0 
     ) else (
      echo %count% >> log.txt 
      set count=0 
     ) 
    REM An animal has been found 
    ) else (
     FINDSTR /R ".Dog.*" tempfile.txt > NUL 
     if NOT errorlevel 1 (
      set \A count+=1 
     ) 
    ) 
) 
del tempfile.txt 
echo %count% >> log.txt 
pause 

所以基本上這是如何代碼的作品是我必須打印出當它讀取新列表頭(List1和List2)時發現了多少「狗」。第一次發生這種情況時,計數將爲零,因爲它也是sample.txt文件的第一行。例如,在讀取List1之後,它會一直讀取,直到找到List2,計數爲1.然後,計數重置爲0,因爲它正在讀取一個新列表。在批處理文件讀取第二個列表時,因爲它也是最終列表,所以它需要輸出它的數量。

* first_iteration *變量記錄批處理文件是否正在讀取第一個列表,以便它知道何時不輸出計數。但問題是,* first_iteration *的值不會改變,因爲批處理如何在單行命令中解釋變量值(如果仔細觀察所有if/else語句是否包含在一組括號中)。

那麼有沒有辦法以批處理文件的形式實現我的目標?

回答

1

您可以使用!first_iteration!進行延遲評估。在使用SETLOCAL ENABLEDELAYEDEXPANSION啓用它之後,您需要在腳本中的多個位置使用它。

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 
set count=0 
set first_iteration=1 

for /f "tokens=*" %%A in (sample.txt) do (
    echo %%A > tempfile.txt 

    FINDSTR /R ".*List.*" tempfile.txt > NUL 

    REM If true, this is a list header 
    REM your post was missing the NOT here 
    if NOT errorlevel 1 (
     if !first_iteration! EQU 1 (
      SET first_iteration=0 
     ) else (
      echo !count! >> log.txt 
      set count=0 
     ) 
    REM An animal has been found 
    ) else (
     REM your post was missing the first * on this line 
     FINDSTR /R ".*Dog.*" tempfile.txt > NUL 
     if NOT errorlevel 1 (
      REM your post used a \ instead of a/here 
      set /A count=1+!count! 
     ) 
    ) 
) 
del tempfile.txt 
echo %count% >> log.txt 
+0

工作就像一個魅力!非常感謝! – Dan

2

假設我的批處理文件的目標是輸出單詞「Dog」在每個列表中出現多少次 次。

SET counter=0 
SETLOCAL ENABLEDELAYEDEXPANSION 
FOR /F "USEBACKQ tokens=*" %%F IN (`TYPE "C:\Folder\sample.txt" ^| FIND /I "dog"`) DO (
    SET /a counter=!counter!+1 
) 
ECHO Dog shows up !counter! many times in this file. 

沒有測試......不記得,如果你應該使用!或當循環後調用計數器時的百分比...