Name: bismarkcount Date: March 3, 2008 at 13:49:12 Pacific Subject: BATCH text file content to variable OS: WinXP CPU/Ram: Intel core 2 Duo Model/Manufacturer: dell
Comment:
D u know how to save the contents of a file into a variable in a MS DOS Batch program?
I have a file called badhost.txt containing information like:
123.21.14.152 123.21.14.155
and i want to save the content of that file in a variable, so if i echo that variable, it will show me the content of the text. I need the information of the file stored in a variable so that i can pass it as a parameter to a program.
Assuming it is Windows XP batch files you're talking about (and not MS-DOS batch) then you can put the contents of a file into a variable by adding all the lines of the file together. Something like this:
@echo off setlocal enabledelayedexpansion set SEPARATOR=/ set filecontent= for /f "delims=" %%a in ("file.txt") do ( set currentline=%%a set filecontent=!filecontent!%SEPARATOR%!currentline! ) echo The file contents are: %filecontent%
Caveats: (1) If the file is large, your environment will run out of space and you will not be able to place the file's entire contents into your variable. (2) The above loop will skip any blank lines. (3) The filecontents variable will still be just a single line, as variables can't hold multiple lines.
It's more a matter of programming style and preference, rather than "better." Many programmers don't like having "magic numbers" in their code, and the set SEPARATOR=/ is a bit like #define CONSTANT in C - you define it once at the top and use it wherever you need to; if later you think you need a different separator you only need to change it once (at the top.) In this example the separator is only used once, but imagine a more complex batch file that uses that separator multiple times: if you need to change it from / to, say, \, you'll have to search for all occurrences of / and then decide if that character in that context really is being used as a separator or something else. But if you use the symbolic name, no problem.
The information on Computing.Net is the opinions of its users. Such
opinions may not be accurate and they are to be used at your own risk.
Computing.Net cannot verify the validity of the statements made on this site. Computing.Net and Computing.Net, LLC hereby disclaim all responsibility and liability for the content of Computing.Net and its accuracy.
PLEASE READ THE FULL DISCLAIMER AND LEGAL TERMS BY CLICKING HERE