0

I am having an issue with a section of code designed to count the number of times a string appears in a text file. It will work perfectly when pasted into command prompt, but when run as a .bat file it immediately closes before completing (It doesn't perform the pause before the last echo command).

set Logpath="C:\Users\bob\Desktop\project\a.txt"
set StringToLookFor="asdf"

set NUM=0
for /F %N in ('find /C %StringToLookFor% ^< %Logpath%') do set NUM=%N
pause
echo %NUM%
  • Since you say "immediately closes" i assume you are double clicking the .bat file. You can try to run it on the command prompt, or adding cmd /k to the top of the bat file to keep the terminal open after you dbl click it (or do the link+do not close option). This will show you the error... it might be failing before the pause. – Gabriel Jul 30 '20 at 23:34
  • When I do that it returns the expected result with no error. – lucasr48 Jul 30 '20 at 23:42
  • 😅 i confess i am not a proficient windows user. I only know a few tricks, and I am happy on linux where things are a little more predictable. But happy that works now. Good lucky figuring out why though... – Gabriel Jul 30 '20 at 23:46
2

adding a second % before N apparently fixed it.

set Logpath="C:\Users\bob\Desktop\project\a.txt"
set StringToLookFor="asdf"

set NUM=0
for /F %%N in ('find /C %StringToLookFor% ^< %Logpath%') do set NUM=%%N
pause
echo %NUM%
  • 1
    This is the solution. Use % when in CMD and %% when writing a batch file. – GChuf Jul 31 '20 at 8:23
0

If you need it to pause for a specific amount of time, how about using timeout?

timeout /t 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.