Search code examples
windowsbatch-filecmd

Reading & Writing a single line of a string variable to a text file in batch script..?


I'm making a small program/routine in batch script;

whereby I ask a user to input an ip address.

I want to take that input, & save it,

& load it the next time the program runs so that it could be processed without user inputting it again. here's a summary/snippet of my code

:load
< lastip.txt (
I want to load %ip%
)

:choice
rem if lastip.txt exists
rem redirects user to somewhere
rem else goes to start depending upon user input

:start rem User inputs Ip here
cls
echo.
echo Input ip, its ipv4 I guess.
set /p %ip%="ip: "
goto save

:save
(
I want To save %ip%
) > lastip.txt
pause
goto somewhere

maybe this has been asked before but I wasn't able to implement any existing solutions in this use case; forgive me.. batch-scripting used to be so easy, maybe I'm not getting along with the syntax, hoping some one could help me on this holy platform?

edit: initially I asked;

Saving & Loading a string variable in batch script..?

later I realized that saving and loading is not the same as reading and writing.. at least in my use case so I changed the question, Lol.


Solution

  • If you're just using one line of text file,

    To save it as the first, and only line of your text file, use either

    1> "lastip.txt" (Echo=%ip%)
    

    OR

    (Echo=%ip%) 1> "lastip.txt"
    

    To load it from the first line of your text file, use either

    0< "lastip.txt" (Set /P "ip=") 
    

    OR

    (Set /P "ip=") 0< "lastip.txt"
    

    From textbook point of view; instead of saving & loading this is rather writing & reading from a text file using batch script if I'm not wrong but it should get the job done.

    I would however be eager to know more on this if anyone else could redirect. that would be great.

    thanks to @compo for the courtesy of this answer.