Fazle Rabbi
Fazle Rabbi

Reputation: 286

read a file line by line and save it in variable batch file

I have the following .txt file:

Marco
Paolo
Antonio

I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is name, the flow is:

Upvotes: 1

Views: 17469

Answers (2)

FifthAxiom
FifthAxiom

Reputation: 300

I think this answers your question.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "somefile=somefile.txt"
if not exist %somefile% (
    echo File '%somefile%' does not exist^^!
    goto :eof
)
for /f "delims=" %%i in (%somefile%) do (
    set "name=%%i"
    set "first=!name!"
    echo !first!
)

Upvotes: 0

Hackoo
Hackoo

Reputation: 18857

This will read a file into an array and assign each line into a variable and display them

@echo off
set "File2Read=file.txt"
If Not Exist "%File2Read%" (Goto :Error)
rem This will read a file into an array of variables and populate it 
setlocal EnableExtensions EnableDelayedExpansion
for /f "delims=" %%a in ('Type "%File2Read%"') do (
    set /a count+=1
    set "Line[!count!]=%%a"
)
rem Display array elements
For /L %%i in (1,1,%Count%) do (
    echo "Var%%i" is assigned to ==^> "!Line[%%i]!"
)
pause>nul
Exit
::***************************************************
:Error
cls & Color 4C
echo(
echo   The file "%File2Read%" dos not exist !
Pause>nul
exit /b
::***************************************************

Upvotes: 2

Related Questions