Travis McCurry
Travis McCurry

Reputation: 11

First Line of Text file to variable in batch

I am trying to pull first line of a .txt file and assign it to variable but inside of a loop. My Variable was not being assigned correctly. It keep displaying "ECHO is off". However, when the loop comes back around, it displays correctly even though it is the same code. How can i get it to display my text i want the first time around?

Code:

@Echo off
:ReadLoop
if exist "<Full\Path\Name>\Note0.txt" (
set /p Var=<"<Full\Path\Name>\Note0.txt"
Echo %Var%
pause>nul
goto :ReadLoop
)

The Output i get is this:

Echo is off.
Note0 Content
Note0 Content
Note0 Content

Upvotes: 1

Views: 1602

Answers (1)

rojo
rojo

Reputation: 24466

Whenever you set a variable within a parenthetical code block, if you want to retrieve that variable within the same code block, you have to do so in the delayed expansion style. For example:

set "test=apples"
(
    set "test=oranges"
    echo %test%
)

... will echo "apples" because that's the value the test variable had when the code block was reached. On the other hand,

set "test=apples"
(
    set "test=oranges"
    setlocal enabledelayedexpansion
    echo %test% and !test!
    endlocal
)

will echo "apples and oranges", because the expansion of !test! is delayed, whereas %test% was not. In a console window, setlocal /? for more information.

Now, apply this knowledge to your code.

@Echo off
setlocal

:ReadLoop
if exist "<Full\Path\Name>\Note0.txt" (
    set /p Var=<"<Full\Path\Name>\Note0.txt"
    setlocal enabledelayedexpansion
    Echo !Var!
    endlocal
    pause>nul
    goto :ReadLoop
)

... will give you the result you expect. You could activate enabledelayedexpansion at the beginning of your script just below @echo off, but doing so can sometimes have adverse effects when setting variable values if those values contain exclamation marks. By all means, feel free, but remember my warning if you ever encounter problems.

Upvotes: 1

Related Questions