Batch for loop find string in variable - for-loop

I want to find the string A in the variable Code=AAABASDG
and count each time 1 up if "A" was found so the result should be that it outputs 4 because in Code variable there are 4 A's
Example Code :
#echo off
set /A C=0
set Code=AAABASDG
for %%i in (%Code%) do IF "%%i"=="A" set /A C=%C%+1
echo %C%
pause

You could get the length of original string A, then delete the "A" letters from the string and get the length of the result, to finally subtract both lengths.
To easily get the length of the string, you could store it in a file and then ask for the %%~Z size of the file. Here it is:
#echo off
setlocal
set "Code=AAABASDG"
> before.txt echo %code%
> after.txt echo %code:A=%
for %%b in (before.txt) do for %%a in (after.txt) do set /A "count=%%~Zb-%%~Za"
echo %count%
The only drawback of this method is that it is not case-aware: both upcase and lowcase letters are delete in the replacement operation

#echo off
set /A C=0
set "Code=AAABASDG"
:loop
if defined code (
if "%code:~-1%"=="A" set /a C+=1
set "code=%code:~0,-1%"
goto loop
)
echo %C%
Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign " or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier.
Substrings in batch are obtained from %var:~m,n% where ,n is optional; m is count-of-chars-from-beginning-of-string, from end if negative. ,n positive = max length to return; negative = end-position in chars from end; missing=return all after m

Here's a quick example which gets help from PowerShell:
#Echo Off
SetLocal EnableExtensions
Set "Code=AAABASDG"
For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
-NoProfile "[RegEx]::Matches('%Code%','A').Count"') Do Set "C=%%G"
Echo(%C%
Pause

Related

Windows Batch SET with Variable Substring Length?

Take this simple example:
#ECHO OFF
SET /P phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO %phrase%
ECHO %rnum%
SET rchar=%phrase:~0,%rnum%%
ECHO %rchar%
Pause
I just want to be able to pass that rnum variable to pick that as the character chosen from the left of that user entered word to that random character.
I can't seem to figure out how to pass that as a variable.
I tried with enabledelayedexpansion with no luck:
#ECHO OFF
SET /P Phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO %phrase%
ECHO %rnum%
setlocal enabledelayedexpansion
SET rchar=!phrase:~0,%rnum%!
endlocal
ECHO %rchar%
Pause
So how do I pass rnum as a variable in this instance? Thanks for any assistance.
Here's a simple modification of your example delayed expansion code, which shows one method of maintaining your variable value beyond endlocal:
#ECHO OFF
SET /P "phrase=Enter Word : "
SET /A rnum = %RANDOM% %% 10 + 1
ECHO %phrase%
ECHO %rnum%
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%G IN ("!phrase:~0,%rnum%!") DO ENDLOCAL & SET "rchar=%%~G"
ECHO rchar=%rchar%
PAUSE
The above example should be fine, as long as the end user does not begin to input strings with problematic characters. If you wanted to make it a little more robust for such scenarios then perhaps this will help:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
:AskString
Rem Get interactive string input
Set "String="
Set /P String="Enter Word : "
If Not Defined String GoTo AskString
Set String
Rem Generate a random integer 1..10
Set /A "Integer = (%RANDOM% %% 10) + 1"
Set Integer
Rem Create a substring variable using %String% and %Integer%
Echo %%SubString%% = %%String:~0,%Integer%%%
SetLocal EnableDelayedExpansion
For /F Delims^=^ EOL^=^ UseBackQ %%G In ('"!String:~0,%Integer%!"') Do (
EndLocal
Set "SubString=%%~G"
)
Set SubString
Pause
Please note that the above code uses Set Variable to display the variable name along side its value. If your variable contains certain poison characters just using Echo %Variable% may not work, and you would probably be better off keeping delayed expansion enabled at that time.
As Compo already comments, the position of your endlocal is the problem.
You could just move the endlocal after the echo
#ECHO OFF
setlocal enabledelayedexpansion
SET /P Phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO !phrase!
ECHO !rnum!
SET "rchar=!phrase:~0,%rnum%!"
ECHO !rchar!
endlocal

string comparison in batch file not working

I have this code:
SETLOCAL enabledelayedexpansion enableextensions
SET OutofService=Weblog_Doc(file:///C:/Bla/BlaKon.htm?send=2000)
REM - Declare and set the Array
FOR /f "delims=" %%a IN (C:\Folder1\log.dat) DO (
SET /a c+=1
SET x[!c!]=%%a
)
REM - Read Array from end to start
FOR /l %%I IN (!c! -1 1) DO (
SET _result=!x[%%I]:~-47%!
ECHO !_result!
ECHO !OutofService!
IF "!_result!"=="!OutofService!" (
ECHO yahooo!
)
)
The string in file log.dat is as follows:
09/17/15 15:18:52:577 Container:
Weblog_Doc(file:///C:/Bla/BlaKon.htm?send=2000)
My ECHO statement is outputting the result:
Weblog_Doc(file:///C:/Bla/BlaKon.htm?send=2000)
Weblog_Doc(file:///C:/Bla/BlaKon.htm?send=2000)
The if statement is returning false and not outputting yahooo! as it should, given the fact that these two strings should be equal. What am I doing wrong?
SET x[!c!]=%%a
^^^^^^^^^^ Spaces included in value
....
SET _result=!x[%%I]:~-47%!
^^^^^^ Spaces included in value
Try with (percent sign in the third line is not needed)
SET "OutofService=Weblog_Doc(file:///C:/Bla/BlaKon.htm?send=2000)"
....
SET "x[!c!]=%%a"
....
SET "_result=!x[%%I]:~-47!"
This way, while the assignment operation is quoted, the quotes are not included in the value, nor the ending spaces if present.

How to extract the numbers after a character in windows batch files

Hi I do need to extract the last part of a string after the last dot
Example:
1.2.37 ==> I need the 37
1.2.567 ==> I need the 567
as you can see the number of characters after the dot is not fixed so expressions like
base=%fullver:~0,-2%
Can't be used. How can I achieve this?
#echo off
setlocal enableextensions disabledelayedexpansion
set "fullver=1.2.456"
for %%a in ("%fullver:.=\%") do set "base=%%~na"
echo %base%
The trick is to replace the dots with backslashes, process the string as a path and retrieve the name of the last element in it.
Alternatively, if all the elements need to be retrieved, instead of a for, a for /f is used to tokenize the variable using the dots as separators
#echo off
setlocal enableextensions disabledelayedexpansion
set "fullver=1.2.456"
for /f "tokens=1-3 delims=." %%a in ("%fullver%") do (
set "major=%%a"
set "minor=%%b"
set "build=%%c"
)
echo [%major%] [%minor%] [%build%]
I found the following question which actually tokenizes the string.
How to split a string in a Windows batch file?
May be you can try using this to delimit it with "." and take the last value stored in the string variable. Not sure if there is a simple way, but this works.
Here is an edited Version to fit your Needs:
#echo off
setlocal ENABLEDELAYEDEXPANSION
REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=1.2.5.234
for /f "tokens=1 delims=." %%a IN ("!teststring!") DO set firststring=%%a
echo !firststring!
REM Do something with each substring
:stringLOOP
REM Stop when the string is empty
if "!teststring!" EQU "" goto END
for /f "delims=." %%a in ("!teststring!") do set substring=%%a
REM Now strip off the leading substring
:striploop
set stripchar=!teststring:~0,1!
set teststring=!teststring:~1!
if "!teststring!" EQU "" goto stringloop
if "!stripchar!" NEQ "." goto striploop
goto stringloop
:END
echo !substring!
endlocal
I prefer MC ND's answer if you are looking for only the last node, or if you know how many nodes there are.
Here is a method to capture all nodes if the total number of nodes is unknown:
#echo off
setlocal enableDelayedExpansion
set "fullver=1.2.456"
:: Parse each node and store in an "array"
set cnt=0
for %%A in (%fullver:.= %) do (
set /a cnt+=1
set "node.!cnt!=%%A"
)
:: Show the results
for /l %%N in (1 1 %cnt%) do echo node.%%N = !node.%%N!
Another solution! This one gets the first and last parts of the string:
#echo off
setlocal
set "testString=1.2.5.234"
set "first="
for %%a in ("%testString:.=" "%") do (
if not defined first set "first=%%~a"
set "last=%%~a"
)
echo First: %first%
echo Last: %last%
As a bonus, this method correctly process special Batch characters that may appear in the string, excepting wild-cards.
You can use the below command to achieve what you want.
base=%fullver:~~4,3%
4 implies 4th digit i.e., 5 and 3 implies 3 digits from 4.
The output will be
567

Increase number in string in bat file?

How can I increment the value of an int in a string ?
Say I have foo-815-bar. I'd like to have foo-815-bar.
foo and bar can be constants (although if bar can be an unknown variable, it would be preferable), and 815 is a variable. It's a 3 digit number that is to be incremented, so that foo-123-bar would return foo-124-bar.
Example:
#echo off
set "string=foo-123-bar"
for /f "tokens=1-3 delims=-" %%i in ("%string%") do (
set "pre=%%i"
set /a number=%%j+1
set "post=%%k"
)
set "string=%pre%-%number%-%post%"
echo %string%
.. output is:
foo-124-bar
This should get you started... you might have to place this inside a loop depending on your needs.
#echo off
set myFoo=foo-
set myBar=-bar
set /a myIncrementor=123
echo %myFoo%%myIncrementor%%myBar%
set /a myIncrementor+=1
echo %myFoo%%myIncrementor%%myBar%

windows batch file array extraction counter not being incremented by +=

I am translating a shell script to windows batch. What I need to do is take all except 1,2 and last from command line arguments. join them and send to another program as argv.
#echo off
SET subject=%1
set count=%2
set candidates=""
set /a i=0
set /a c=0
FOR %%A IN (%*) DO (
ECHO %%A
set /a i+=1
IF %i% geq 2 (
set /a c+=1;
set candidates[!c!]=%%A
)
)
SET /a count_actual=(%i%-3)
SET /a count_expected=%count%
echo %count_expected%
echo %count_actual%
echo %subject%
echo %candidates%
I want the candidates array be argv[3..n-1]
e.g. If I write batch x 2 a b p it should pass a b to that another program
The problem is loop counter is not being incremented by += operator. If I write echo %1% inside FOR I see 0 always
You should not use for %%A in (%*) as it treats %* as filename set. This may cause problems, especially if you can pass * or ? (wildcard match characters in cmd) in parameters - as they will be expanded to all files satisfying pattern. Second, batch does really know nothing about arrays - a[1] and a[2] are just a shorthand notation for humans - they are two distinct variables.
Given the problem Parse command line, take second parameter as count of parameters to concatenate into a variable, here is my take:
#echo off
setlocal
set subject=%1
shift
set exp_count=%1
if not defined exp_count (
echo Count not specified
exit /b 1
)
set /a "verify=%exp_count%"
if %verify% leq 0 (
echo Count not valid /not a positive integer/
exit /b 2
)
set real_count=0
:loop
shift
if "%~1"=="" goto end_params
set /a real_count+=1
if %real_count% leq %exp_count% set "candidates=%candidates%%~1"
goto loop
)
:end_params
if %real_count% lss %exp_count% (
echo Less parameters passed than specified!
exit /b 3
)
echo %subject%
echo %candidates%
Please note I'm not checking if there is a 'hanging' parameter (the last, not being concatenated) but it should be trivial to add that check. I left it out on purpose to make the code more flexible.
I have two answers for your question:
1- The first problem is that in IF %i% ... command the value of i variable not change (although set /a i+=1 command will correctly increment the variable) and the way to solve it is by including setlocal EnableDelayedExpansion command at beginning and enclose i in percents signs this way: IF !i! ... (as said in previous answers). However, you must note that an array variable in Batch is different than a simple variable with same name (they both can exist at same time), so array elements must always be written with subscripts and there is NO way to process an entire array in a single operation. See this topic for further details.
In your program you must transfer the elements of candidates array into a simple variable, that in the example below have the same name (just to state my point):
#echo off
setlocal EnableDelayedExpansion
SET subject=%1
set count=%2
set candidates=""
set /a i=0
set /a c=0
FOR %%A IN (%*) DO (
ECHO %%A
set /a i+=1
IF !i! geq 2 (
set /a c+=1
set candidates[!c!]=%%A
)
)
SET /a count_actual=(%i%-3)
SET /a count_expected=%count%
echo %count_expected%
echo %count_actual%
echo %subject%
REM Transfer "candidates" array elements into "candidates" simple variable:
set candidates=
FOR /L %%i IN (1,1,%c%) do (
set candidates=!candidates! !candidates[%%i]!
)
REM Show "candidates" simple variable:
echo %candidates%
Note that in Batch files you may insert commas, semicolons and equal-signs as separators instead spaces in most commands. However, SET /A command have other rules at this respect, so the semicolon must be omitted.
2- Independently of the array management explained above, this is the way I would solve your problem using a list instead of an array:
#echo off
SET subject=%1
shift
set count=%1
set candidates=
set lastArg=
set i=0
:nextArg
shift
if "%1" equ "" goto endArgv
set /a i+=1
set candidates=!candidates! !lastArg!
set lastArg=%1
goto nextArg
:endArgv
SET /a count_actual=i-3, count_expected=count
echo %count_expected%
echo %count_actual%
echo %subject%
echo %candidates%
Antonio
Yes your code will not increment i. Batch variable replacement occurs when a block is parsed, not when it is executed. The entire for block is parsed once, so %i% is replaced with zero before the for block is executed.
To disable that you need to enable delayed expansion and change your variable escape characters from %'s to !'s to have the replacement made at runtime. Then you will see i incremented in the for loop.
#echo off
Setlocal EnableDelayedExpansion
SET subject=%1
set count=%2
set candidates=""
set /a i=0
set /a c=0
FOR %%A IN (%*) DO (
ECHO %%A
set /a i+=1
IF !i! geq 2 (
set /a c+=1
set candidates[!c!]=%%A
)
)
SET /a count_actual=(%i%-3)
SET /a count_expected=%count%
echo %count_expected%
echo %count_actual%
echo %subject%
echo %candidates%
You will also need to get rid of the ; at the end of the set /a c+=1; line and I'm not sure what you are trying to do on line set candidates[!c!]=%%A as the brackets don't mean anything in batch.
While there are a bunch of answers already listed, I decided to add one more. My approach is to keep the answer as simple as possible for your specific needs. If you have any questions feel free to ask.
This will create the array as you desired [3,...,n-1] without the need for delayed expansion or fancy logic.
#echo off
:: Get the First Two Parameters
set "subject=%1"
shift
set "count=%1"
shift
:: Loop through the rest
set "index=0"
:NextParam
set "param=%1"
shift
set "next=%1"
:: Skip the last parameter
if not defined next goto EndParam
set "candidates[%index%]=%param%"
set /a "index+=1"
goto NextParam
:EndParam
set "count_actual=%index%"
set "count_expected=%count%"
:: Show the Results
echo %count_actual%
echo %count_expected%
echo %subject%
set candidates
Here is an alternate where the candidates are stored in a space delimited string instead of seperate variables. Replace the space between the %candidates% %param% to whatever delimiter you desire.
#echo off
:: Get the First Two Parameters
set "subject=%1"
shift
set "count=%1"
shift
:: Loop through the rest
set "index=0"
:NextParam
set "param=%1"
shift
set "next=%1"
:: Skip the last parameter
if not defined next goto EndParam
set "candidates=%candidates% %param%"
set /a "index+=1"
goto NextParam
:EndParam
set "count_actual=%index%"
set "count_expected=%count%"
:: Show Results
echo %count_actual%
echo %count_expected%
echo %subject%
echo %candidates%

Resources