0

I used code below

set var=mystringstring
echo %var%|find /c "str"

and it returned 2 as expected.

However, when I try to store it in a variable like

set var=mystringstring
set var= echo %var%|find /c "str"

it returned 0, and var remained mystringstring.

4
  • I think you need to look at - SETLOCAL EnableDelayedExpansion. The variable is then addressed as !var!. Commented Sep 14, 2018 at 8:33
  • This isn't BASH. To capture the output of a command in a Windows Batch File you use a FOR /F command. Commented Sep 14, 2018 at 12:07
  • @Squashman I know I can use FOR /F but It seems silly to use loops on a single result, which is the number of times of presence. Commented Sep 14, 2018 at 17:42
  • 2
    Your code example actually does not output two. The FIND command only counts occurrences once per line. Your code example only outputs one. Commented Sep 14, 2018 at 17:56

1 Answer 1

2

If you want to count the number of occurrences of string within another string you can do this.

@echo off
set var=mystringstring
set n=0
set x=%var%
set "x=%x:str=" & set /a n+=1 & set "x=%"
echo The string "str" occurs %n% time(s) in "%var%"
pause
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, this is obvious... ;) +1
@Aacini, “Good artists copy, great artists steal”
I don't really understand the line set "x=%x:str=" & set /a n+=1 & set "x=%". Could you please tell me how it works(I guess it counts once per replacement).
@microwaver, the trick is the substitution with the set command. For every occurrence of the string it is replacing it with another set command to iterate the number of occurrences. The best way to visualize it is to actually see it. Turn ECHO ON at the top of the script and watch it execute. Once you see how the actual code is executing it will be very clear.

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.