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.

2 Answers 2

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!
Sign up to request clarification or add additional context in comments.

4 Comments

Same thing can be achieve in much simple way. But it not solve my problem.
But what is your concrete problem? If you can read the file, line by line you could examine each line.
My object is to assign either all lines to single variable or each line per variable.
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.