Batch Command to Pull Variables from a Text File

Batch Command to Pull Variables from a Text File

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)?

4 Answers

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.

set /p var=<directory\file.txt

that will grab the first line out of a text document.

9

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

@echo off
set str=^&Type file.txt
echo %str%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.