How to set commands output as a variable in a batch file

前端 未结 9 1280
我在风中等你
我在风中等你 2020-11-22 01:19

Is it possible to set a statement\'s output of a batch file to a variable, for example:

findstr testing > %VARIABLE%

echo %VARIABLE%
9条回答
  •  别那么骄傲
    2020-11-22 01:56

    If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

    FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
    echo %VARIABLE%
    

    If you want to enclose search string in double quotes:

    FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i
    

    If you want to store this code in a batch file, add an extra % symbol:

    FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i
    

    A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

    FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i
    

    Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokens or usebackq in for loop.

    Tested on Win 10 CMD.

提交回复
热议问题