Is it possible to set a statement\'s output of a batch file to a variable, for example:
findstr testing > %VARIABLE%
echo %VARIABLE%
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
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
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.