Reputation: 167
Is there any command for a batch file to read a text file, and use the content as a variable? A while back I'd heard about a command that could read the last line of a text file and assign this as a variable in the batch file, but I can't remember what the command was or if it even worked. Is there such a command? I've tried things like:
Set /a var < directory.bat\file.txt
which returns a value of 0, or
Set /p var < directory.bat\file.txt
or
Set /i var < directory.bat\file.txt
, which gives the error "the syntax of a command is incorrect. Am I on the right track with "set" commands, or is there a completely different command for this (or will I have to write an entire different, multi-line script to do this)?
Upvotes: 2
Views: 39003
Reputation: 80023
The classic form of this operation is
for /f "delims=" %%a in (file.txt) do set var=%%a
which will set var
to the entire contents of the last non-blank line.
for /f "delims=" %%a in (file.txt) do set var=%%a&goto next
:next
will set var
to the first non-blank line
for /f "delims=" %%a in (file.txt) do set var=%%a&call :process
...
:process
echo var=%var%
goto :eof
will execute a subroutine with var
set to each non-blank line in turn.
Without sample data, it's not possible to detemine which form suits your situation.
Upvotes: 4
Reputation: 233
here's an awk command you can use
@echo off
for /f "tokens=*" %%a in ('awk "!/^$/{s=$0}END{print s}" myFile.txt') do (
echo last line is %%a
)
you can download awk here or here
Upvotes: 1
Reputation: 5197
set /p var=<directory\file.txt
that will grab the first line out of a text document.
Upvotes: 3