JSI Tip 10130. How can I set a variable equal to the first line of a file?

To set a variable to the contents of a file, we normally use the FOR command, as in:

for /f "Tokens=*" %%a in ('type c:\boot.ini') do (
 set var=%%a
This sets the variable to each line in the file.

To get only the first line, one could use:

set first=Y
for /f "Tokens=*" %%a in ('type c:\boot.ini') do (
 if "!first!" EQU "Y" set first=N&set var=%%a
While the above technique works, the computer still processes every record in the file.

A better way to set a variable to the first line of a file is:

set /p VariableName=<FileName


set /p var=<c:\boot.ini

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.