How do I loop through ASCII values (here, alphabets) and work on them?
I want to echo A to Z without having to type every character manually like
for %%J in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do echo %%J
So I was wondering if I can cycle through ASCII codes. Something like for %%J in (ASCII of A ie.65 to Z) do echo %%J
Any help would be appreciated.
In Batch Script, the variable declaration is done with the %% at the beginning of the variable name. The IN list contains of 3 values. The lowerlimit, the increment, and the upperlimit. So, the loop would start with the lowerlimit and move to the upperlimit value, iterating each time by the Increment value.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.
The "delims=" option means do not parse into tokens (preserve each entire line). So each line is iteratively loaded into the %%i variable.
Surprisingly, there is a solution that makes use of an undocumented built-in environment variable named =ExitCodeAscii
, which holds the ASCII character of the current exit code1 (ErrorLevel
):
@echo off
for /L %%A in (65,1,90) do (
cmd /C exit %%A
call echo %%^=ExitCodeAscii%%
)
The for /L
loop walks through the (decimal) character codes of A
to Z
. cmd /C exit %%A
sets the return code (ErrorLevel
) to the currently iterated code, which is echo
-ed as a character afterwards. call
, together with the double-%
-signs introduce a second parsing phase for the command line in order to get the current value of =ExitCodeAscii
rather than the one present before the entire for /L
loop is executed (this would happen with a simple command line like echo %=ExitCodeAscii%
). Alternatively, delayed expansion could be used also.
The basic idea is credited to rojo and applied in this post: How do i get a random letter output in batch.
1) The exit code (or return code) is not necessarily the same thing as the ErrorLevel
value. However, the command line cmd /C exit 1
sets both values to 1
. To ensure that the exit code equals ErrorLevel
, use something like cmd /C exit %ErrorLevel%
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With