1

I want to store the output of text file into a variable, so I can pass the whole file as parameter.

I am using Windows 2003 Server.

The text files have multiple lines like:

10.20.210.100 fish
10.20.210.101 rock

I was using:

Set /P var=<file.txt

It reads only the first line of the file.

I tried with FOR loop also but it assigned only the last line to the variable.

Hal Mueller
  • 7,019
  • 2
  • 24
  • 42
Rock with IT
  • 361
  • 3
  • 5
  • 14

2 Answers2

2

There is no simple way to get the complete content of a file into one variable. A variable has a limit of ~8100 length. And it is complicated to get CR/LF into a variable

But with a FOR-loop you can get each single line.

Try a look at batch script read line by line

EDIT: To get each line in a single variable you can use this

@echo off
SETLOCAL EnableDelayedExpansion
set n=0
for /f "delims=" %%a IN (example.txt) do (
  set /a n+=1
  set "line[!n!]=%%a"
  echo line[!n!] is '%%a'
)
set line

or to get all in only one variable (without CR/LF)

@echo off
SETLOCAL EnableDelayedExpansion
set "line="
for /f "delims=" %%a IN (example.txt) do (
  set "line=!line! %%a"
)
echo !line!
Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Same thing can be achieve in much simple way. But it not solve my problem. – Rock with IT Jan 03 '11 at 12:44
  • But what is your concrete problem? If you can read the file, line by line you could examine each line. – jeb Jan 03 '11 at 12:47
  • My object is to assign either all lines to single variable or each line per variable. – Rock with IT Jan 03 '11 at 12:50
  • Thanx jeb. But if you echo %line% it contains each line no of line in file times. And if you use echo! Line! ,it contain one !line! also with other line. I did a little modification in script and now I am getting expected result. – Rock with IT Jan 04 '11 at 07:15
0

Jeb’s script is working perfect, But if you echo %line% it contains each line no of line in file times. And if you use echo !Line! ,it contain one !line! also with other line. I did a little modification in script and now I am getting expected result.

@echo off
SETLOCAL EnableDelayedExpansion
set "line="
for /f "delims=" %%a IN (example.txt) do (
set "line1=%%a"
set "line=!line1! and  %%a"
)
echo !line!

or

echo %line%

Now you will get same result in bot cases.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Rock with IT
  • 361
  • 3
  • 5
  • 14