Re: simple windows batch file question

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance




<pault.ng@xxxxxxxxxxxxx> wrote in message
news:1119099470.090033.259760@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> Hi,
>
> How do I assign the program output to a variable in a batch file?
>
> I guessed it would be something like:
>
> set MY_VAR = `type filename`
> echo %MY_VAR%
>
> I want to assign the one line that is in the file to be assigned to
> MY_VAR.
>
> Thanks,
>
> Paul.
>

Sort of depends on precisely what you want to do.

(following examples are for use WITHIN a batch file - to execute direct from
the prompt, change each "%%" to "%" - and my sympathies to your typing
finger.)

If you want to assign the LAST line in a file to a variable, try

for /f "delims=" %%i in (filename.txt) do set varname=%%i

If you want to assign the FIRST line in a file to a variable, try

set varname=
for /f "delims=" %%i in (filename.txt) do if not defined varname set
varname=%%i

and if you want to assign an arbitrary line numbered line to the variable,
try

set varname=
for /f "skip=linenumberrequired-1,delims=" %%i in (filename.txt) do if not
defined varname set varname=%%i

Noting that for/f automatically disregards empty lines

If you actually want to assign a line from the output of a command, then
replace filename.txt with 'command command_parameters' - for instance, the
third line from a DIR /S /B command:

set varname=
for /f "skip=2,delims=" %%i in ('dir /s /b') do if not defined varname set
varname=%%i

noting the the single-quotes are REQUIRED.

There are of course more complex methods depending on quite what you want to
do. Newsgroup alt.msdos.batch.nt is a discussion group which tackles twisted
batch methods for NT/2K/XP... alt.msdos.batch for realDOS and 9x

HTH

....Bill


.