simple windows batch file question

P

pault.ng

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.
 
W

William Allen

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.

In a Batch file, use:

FOR /f "tokens=*" %%A IN (FileName.txt) DO SET MyVar=%%A

For help with syntax of FOR, use the /? switch
for /?
 
B

billious

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top