1

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:

  • Read first line from file
  • Assign name = "Marco"
  • Do some tasks with name, let sat set first= %name%
  • Read second line from file
  • Assign name = "Paolo" How do I do it?
Fazle Rabbi
  • 231
  • 1
  • 5
  • 17
  • 4
    From command line read the output of `for /?` (look for the `for /f` syntax to process files) and `set /?`, `setlocal /?` (read about `delayed expansion`) – MC ND Jan 29 '17 at 19:36
  • 4
    Possible duplicate of [Windows Batch help in setting a variable from command output](http://stackoverflow.com/questions/1746475/windows-batch-help-in-setting-a-variable-from-command-output). Read Joey's answer. – JosefZ Jan 29 '17 at 20:17
  • See my answer: stackoverflow.com/a/74947553/8353248 – FifthAxiom Dec 29 '22 at 08:07

2 Answers2

2

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
::***************************************************
Hackoo
  • 18,337
  • 3
  • 40
  • 70
0

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!
)
FifthAxiom
  • 172
  • 1
  • 7