0

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
  • 201
  • 1
  • 3
  • 12
  • 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

1 Answers1

1

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
  • 16,942
  • 3
  • 35
  • 62