In a recent post, Jeb mentioned the How SET /P Works article located
at:
http://www.dostips.com/forum/viewtopic.php?f=3&t=2160
which led me (after much Googling) to this thread on an ss64.com
forum:
http://ss64.org/viewtopic.php?id=104
And I began to think to myself how useful it would be to be able to
set
the output of a command to a variable. Like the EXPORT command in
Linux/Unix:
EXPORT var=`cmd`
In fact, there's a free Windows port available (32 and 64-bit) from:
http://www.xeox.com/index.php/en/tools/exportexe
But you can't rely on that software being installed on the system you
find
yourself using at work or for a project, so how about something
written in
pure Batch, and doesn't use temporary files or delayed expansion?
Well, bearing in mind all the caveats outlined in the How SET /P
Works
article, and modifying Dan9999's workaround from the ss64.com forum, I
came up with this rough draft...
:: export.cmd
@echo off & setlocal enableextensions disabledelayedexpansion
if "%~1" neq "" (call :_export "%~1" & goto _bypass)
more /e +[line_no-1] [file.txt] | %ComSpec% /c "%~f0" line
goto _end
:_bypass
if defined line (echo:line="%line%") else echo:^<blank line^>
:_end
endlocal & exit /b 0
:_export
set var=%~1
set /p %var%=
goto :EOF
:: end of export.cmd
Btw, the above also demonstrates how to store the nth line of a CRLF
text
file in a variable.
Apologies if this is old news to you. I tried searching the
archive.
The only result with a promising subject line turned out to be a flame
war
from years back about the future of the newsgroup. Anyways, feel free
to
improve/obfuscate my ver0.1 beyond all recognition. All I ask is that
you add a few comments as you go. Remember that I am a mere
apprentice in
the company of wizards,
toodles,
John
This can be done using the FOR command to capture the output.
for /f "delims=" %%a in ('the_cmd') do set "var=%%a"