PeterS
PeterS

Reputation: 724

How to set string with spaces (from contents of a file) in a variable using batch script

I have this code that reads the content of a file and set all the contents in a variable.

for /f "tokens=1,*" %%h in ('type C:\user\userfiles\title.txt') do (
set title=%%h
)echo %title%

Example contents of title.txt

AAAA BBBB CCCC

Now, It always display the word before the first space. How to display all contents of a file in variable title?

Upvotes: 0

Views: 81

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6598

You need to specify that there should be no delimiters in the FOR parameters, otherwise a space will be used and only pick up the first value:

REM Pick up a single token with no delimiters.
REM This will read the entire line of the file.
for /f "usebackq tokens=* delims=" %%h in (`type "C:\user\userfiles\title.txt"`) do set title=%%h
echo %title%

Note that if the file has multiple lines, only the last line will be set to the %title% variable.

If you want to then turn around and use the result of %title% as a parameter to a program, make sure you put it in quotes as it may contain spaces:

SomeProgram.exe "%title%"

Upvotes: 2

Related Questions