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

前端 未结 9 1265
我在风中等你
我在风中等你 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:54

    To read a file...

    set /P Variable=<File.txt
    

    To Write a file

    @echo %DataToWrite%>File.txt
    

    note; having spaces before the <> character causes a space to be added at the end of the variable, also

    To add to a file,like a logger program, First make a file with a single enter key in it called e.txt

    set /P Data=<log0.log
    set /P Ekey=<e.txt
    @echo %Data%%Ekey%%NewData%>log0.txt
    

    your log will look like this

    Entry1
    Entry2 
    

    and so on

    Anyways a couple useful things

    0 讨论(0)
  • 2020-11-22 01:55

    I most cases, creating a temporary file named after your variable name might be acceptable. (as you are probably using meaningful variables name...)

    Here, my variable name is SSH_PAGEANT_AUTH_SOCK

    dir /w "\\.\pipe\\"|find "pageant" > %temp%\SSH_PAGEANT_AUTH_SOCK && set /P SSH_PAGEANT_AUTH_SOCK=<%temp%\SSH_PAGEANT_AUTH_SOCK
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题