0
@echo off
set /a count = 0
for /f "delims=" %%a in ('dir "%~1" /a:-d /b') do call :next "%%a" "%~2"
echo found %count% occurances of "%~2"
pause
GOTO:EOF
:next
set num=
for /f "delims=" %%b in ('find /c %2 ^< %1') do set num=%%b
set /a count=count+num

My code is wrong count of the text specified in the parameter. What's the problem?

5
  • I tried running this, it failed if I didn't match the case of the text, but worked fine otherwise. Commented Nov 5, 2013 at 16:37
  • If the specified sequence occurs several times in a row it counts as one. Commented Nov 5, 2013 at 17:21
  • 2
    find will count the number of lines that match your string, so searching xyyx' for 'x' will count as one, even though the x's aren't in a row. If that's not what you want, you'll need a different tool. Commented Nov 5, 2013 at 17:24
  • @Mark - just post this as answer Commented Nov 5, 2013 at 17:54
  • In summary, it is impossible in batch? Commented Nov 5, 2013 at 18:18

2 Answers 2

1

As Mark said, find return the number of lines that match in a file, not the number of individual strings in one line. To do so, you need to use another method, for example:

@echo off
setlocal EnableDelayedExpansion
set /a count = 0
for /f "delims=" %%a in ('dir "%~1" /a:-d /b') do (
   for /F "delims=" %%b in ('find %2 ^< "%%a"') do call :next "%%b" "%~2"
)
echo found %count% occurances of "%~2"
pause
GOTO:EOF

:next
set num=0
set "line=%~1"
:nextMatch
   set "line2=!line:*%~2=!"
   if "!line2!" equ "!line!" goto endMatchs
   set /A num+=1
   set "line=!line2!"
if defined line goto nextMatch
:endMatchs
set /a count=count+num

For example:

C:> type 1.txt
An example of text file.
This example line have two "example" words.
End of example.

C:> test 1.txt "example"
found 4 occurances of "example"
Sign up to request clarification or add additional context in comments.

4 Comments

I think somewhere there is a mistake, script don't run. my_prog.bat "example" 1.txt
Try my_prog.bat 1.txt "example"
The same. If I type a string, which does not appear correctly returns 0, but I'll type something exist in file it returns an error that the command syntax is incorrect.
Awesome. I never thought that a seemingly simple script proves to be quite complicated. Excellent knowledge and skills, thank you.
1

find will count the number of lines that match your string, so searching 'xyyx' for 'x' will count as one match, even though the x's aren't in a row. If that's not what you want, you'll need a different tool.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.