Loop through ASCII codes in batch file

后端 未结 5 2123
囚心锁ツ
囚心锁ツ 2021-01-04 17:46

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 (

5条回答
  •  难免孤独
    2021-01-04 18:50

    This answer is a compilation and comparison of the methods given before.

    In the question the OP requested to echo A to Z letters in a batch file. If the purpose of the solution is not just show letters, but process the letters in any other way, then the =ExitCodeAscii variable method is the only one that do that with Batch code, although the modification required in the other two methods to do the same is simple.

    The code below include the three methods and compare they in the simplest possible way: via the time required by each one to complete.

    @if (@CodeSection == @Batch) @then
    
    @echo off
    setlocal
    
    set "start=%time%"
    for /L %%a in (65,1,90) do (
        cmd /C exit %%a
        call echo Batch: %%^=ExitCodeAscii%%
    )
    echo First method: using =ExitCodeAscii variable
    echo Start: %start%
    echo End:   %time%
    echo/
    
    set "start=%time%"
    for /F %%a in ('powershell "65..90 | %%{ [char]$_ }"') do echo PS: %%a
    echo Second method: using PowerShell
    echo Start: %start%
    echo End:   %time%
    echo/
    
    set "start=%time%"
    for /F %%a in ('cscript //nologo //E:JScript "%~F0"') do echo JScript: %%a
    echo Third method: using JScript
    echo Start: %start%
    echo End:   %time%
    
    goto :EOF
    
    @end
    
    for (var i=65; i<=90; i++) WSH.Echo(String.fromCharCode(i));
    

    Several executions of this code show consistent results: the PowerShell method is the slowest one, the =ExitCodeAscii method run 280% faster than PowerShell, and JScript method run 240% faster than =ExitCodeAscii. These differences would diminish as the whole program grow and perform more things than just show the letters, but in standard/small Batch files, this relation will always be the same: PowerShell is the slowest method and JScript the fastest one. The VBScript method is similar to JScript.

提交回复
热议问题