2011-11-02 88 views
2

在Windows XP中使用批處理腳本(.bat文件),我將如何去閱讀文本文件並查找存在多少個字符實例?批處理腳本 - 計算文件中字符的實例

例如,我有以下的字符串:

""OIJEFJ"JOIEJKAJF"""LKAJFKLJEIJ""JKLFJALKJF"LKJLKFA""""LKJKLFJLKADJF 

我想這算多少"有在文件中,並返回計數。

+0

以及如何人會解決這個問題?你能解決一行,還是一個字符? – jeb

+0

@jeb請你重申一下這個問題嗎? – Mechaflash

+0

現在我很困惑,我不能翻譯你的評論,我的英文太窮了:-( – jeb

回答

8

讓我們開始對一行中的字符進行計數。首先,緩慢而清晰的方法:

set i=-1 
set n=0 
:nextChar 
    set /A i+=1 
    set c=!theLine:~%i%,1! 
    if "!c!" == "" goto endLine 
    if !c! == !theChar! set /A n+=1 
    goto nextChar 
:endLine 
echo %n% chars found 

現在快和神祕的方法:

call :strLen "!theLine!" 
set totalChars=%errorlevel% 
set strippedLine=!theLine:%theChar%=! 
call :strLen "!strippedLine!" 
set /A n=totalChars-%errorlevel% 
echo %n% chars found 
goto :eof 

:strLen 
echo "%~1"> StrLen 
for %%a in (StrLen) do set /A StrLen=%%~Za-4 
exit /B %strLen% 

最後的方法來計算一個文件中的字符:

set result=0 
for /F "delims=" %%a in ('findstr "!theChar!" TheFile.txt') do (
    set "theLine=%%a" 
    place the fast and cryptic method here 
    set /A result+=n 
) 
echo %result% chars found 
+0

man ...我用過這種方法在...之前單個字符不能相信我已經忘記了,因爲我更好地理解了「Slow」方法,所以我將會使用它 – Mechaflash

+0

刪除字符並獲得長度差異,晚餐聰明:)。 Someone創建快速字符計數在這裏: http://stackoverflow.com/questions/5837418/how-do-you-get-the-string-length-in-a-batch-file – fantastory