Looping for each character in a variable string BATCH

I am trying to skip every character in a string. I only know how to loop for each word in a string using the following:

(set /P MYTEXT=)<C:\MYTEXTFILE.txt set MYEXAMPLE=%MYTEXT% for %%x in (%MYEXAMPLE%) do ( ECHO DO SOMTHING ) 

How can I configure it to work on a character, not per word?

+4
source share
3 answers

AFAIK, FOR cannot iterate character by character. A possible workaround is to create a loop as follows:

 @ECHO OFF :: string terminator: chose something that won't show up in the input file SET strterm=___ENDOFSTRING___ :: read first line of input file SET /P mytext=<C:\MYTEXTFILE.txt :: add string terminator to input SET tmp=%mytext%%strterm% :loop :: get first character from input SET char=%tmp:~0,1% :: remove first character from input SET tmp=%tmp:~1% :: do something with %char%, eg simply print it out ECHO char: %char% :: repeat until only the string terminator is left IF NOT "%tmp%" == "%strterm%" GOTO loop 

Note. The question header says that you want to iterate over “every character in the variable string”, which assumes that the input file contains only one line, because the command (set /P MYTEXT=)<C:\MYTEXTFILE.txt will read only the first line C:\MYTEXTFILE.txt . If you want to iterate over all the lines in a file instead, the solution is a bit more complicated, and I suggest you open another question for it.

+2
source

This is a simple and direct way to scroll through each character in a line:

 @echo off setlocal ENABLEDELAYEDEXPANSION set /P mytext= < MYTEXTFILE.txt echo Line is '%mytext%' set pos=0 :NextChar echo Char %pos% is '!mytext:~%pos%,1!' set /a pos=pos+1 if "!mytext:~%pos%,1!" NEQ "" goto NextChar 
+1
source

The splitStr routine splitStr below:

  • will print each character in a line one by one
  • can be safely called regardless of expansion delay state
  • doesn't have a superslow goto loop
  • handles CR and LF
  • sets errorLevel number of characters per line
 @echo off & setLocal enableExtensions disableDelayedExpansion (call;) %= sets errorLevel to 0 =% set "testStr=uncopyrightable" call :splitStr testStr if errorLevel 1 ( >&2 echo(string is %errorLevel% char(s^) in length ) else ( >&2 echo(empty string goto die ) %= if =% goto end :die (call) %= sets errorLevel to 1 =% :end endLocal & goto :EOF :splitStr string= :: outputs string one character per line setLocal disableDelayedExpansion set "var=%1" set "chrCount=0" & if defined var for /f "delims=" %%A in (' cmd /v:on /q /c for /l %%I in (0 1 8190^) do ^ if "!%var%:~%%I,1!" neq "" (^ echo(:^!%var%:~%%I^,1^!^) else exit 0 ') do ( set /a chrCount+=1 echo%%A ) %= for /f =% endLocal & exit /b %chrCount% 
0
source

All Articles