Capture output command CMD
Platform Windows XP
When writing a command file (.bat) how can i "catch" the output from a command into a variable ?
I want to do something like this
SET CR='dir /tw /-c b.bat | findstr /B "[0-9]"'
But this do not work
Regards Stefan
PS No, I can not dowload grep, cygwin or any other software, it have to be the CMD DS
Solution 1:
You can use FOR /F
and go through some loops inside a batch file to capture the output:
@echo off
setlocal enabledelayedexpansion
set var=
for /f "tokens=* delims=" %%i in ('dir /tw /-c b.bat ^| findstr /B "[0-9]"') do set var=!var!^
%%i
echo %var%
It is especially important that there are two newlines between !var!^
and the %%i
below.
Additionally you need to escape (again using ^
) all characters inside the command line for FOR
that have special meaning to the shell, such as the pipe in this instance.
The solution works by iterating over the output of the command and appending each line to the contents of var
incrementally. To do that in a somewhat convenient manner the script enables delayed variable expansion (the !var!
syntax).
Solution 2:
You can use for /f
for that:
for /f %%L in ('dir /tw /-c b.bat ^| findstr /b "[0-9]"') do set CR=%%L
This assumes that there is only a single line of output, though. You cannot (trivially or usefully) capture more than one line in a variable.
I can only guess what you're really trying to do here, though. If you need the file size (just guessing because of the /-c
) then it's certainly easier to use
for %%X in (b.bat) do set size=%%~zX