Slightly building upon the answers of other people. Now allowing you to specify the file you want to read from and the variable you want the result put into:
@echo off
for /f "delims=" %%x in (%2) do (
set %1=%%x
exit /b
)
This means you can use the above like this (assuming you called it getline.bat)
c:\> dir > test-file
c:\> getline variable test-file
c:\> set variable
variable= Volume in drive C has no label.
Here's a general-purpose batch file to print the top n lines from a file like the GNU head utility, instead of just a single line.
@echo off
if [%1] == [] goto usage
if [%2] == [] goto usage
call :print_head %1 %2
goto :eof
REM
REM print_head
REM Prints the first non-blank %1 lines in the file %2.
REM
:print_head
setlocal EnableDelayedExpansion
set /a counter=0
for /f ^"usebackq^ eol^=^
^ delims^=^" %%a in (%2) do (
if "!counter!"=="%1" goto :eof
echo %%a
set /a counter+=1
)
goto :eof
:usage
echo Usage: head.bat COUNT FILENAME
For example:
Z:\>head 1 "test file.c"
; this is line 1
Z:\>head 3 "test file.c"
; this is line 1
this is line 2
line 3 right here
It does not currently count blank lines. It is also subject to the batch-file line-length restriction of 8 KB.
The problem with the EXIT /B solutions, when more realistically inside a batch file as just one part of it is the following. There is no subsequent processing within the said batch file after the EXIT /B. Usually there is much more to batches than just the one, limited task.
To counter that problem:
@echo off & setlocal enableextensions enabledelayedexpansion
set myfile_=C:\_D\TEST\My test file.txt
set FirstLine=
for /f "delims=" %%i in ('type "%myfile_%"') do (
if not defined FirstLine set FirstLine=%%i)
echo FirstLine=%FirstLine%
endlocal & goto :EOF
(However, the so-called poison characters will still be a problem.)
More on the subject of getting a particular line with batch commands:
@echo off & setlocal enableextensions
set myfile_=C:\_D\TEST\My test file.txt
for /f "tokens=* delims=" %%a in (
'type "%myfile_%"') do (
set FirstLine=%%a& goto _ExitForLoop)
:_ExitForLoop
echo FirstLine=%FirstLine%
endlocal & goto :EOF
@echo off
setlocal enableextensions enabledelayedexpansion
set firstLine=1
for /f "delims=" %%i in (yourfilename.txt) do (
if !firstLine!==1 echo %%i
set firstLine=0
)
endlocal