I want to read a .txt file using batch script. Each line should be stored in a variable.
My problem: I have to give the command a file path to the .txt file. Unfortunately this hasn't worked so far. The solution is probably very simple, but I haven't found it yet.
for /f "tokens=*" %%a in ("%FilePath%backup\packs.txt") do (
Set /a count+=1
Set url[!count!]=%%a
)
echo %url[2]%
for /f
loops can process three different types of data - files, strings, and commands. Each of these is indicated differently when you call the for
command.
A file is processed by not using quotes in the set area: for /f %%A in (file.txt) do (
A command is processed by using single quotes: for /f %%A in ('find "abc" file.txt') do (
A string is processed by using double quotes: for /f %%A in ("hello world") do (
Of course, sometimes you need to process a file with a space in the path, and that's when you'd use the usebackq
option. This option will still process all three types of data, but the indicators will be different.
A file is processed by using double quotes: for /f "usebackq" %%A in ("some file.txt") do (
A command is processed by using backticks: for /f "usebackq" %%A in (`find "don't" file.txt`) do (
A string is processed by using single quotes: for /f "usebackq" %%A in ('19^" screen') do (
Either removing the quotes from your file path or adding the usebackq
option will set the variables for you.
@echo off
setlocal enabledelayedexpansion
set "FilePath=.\test_path\"
set "count=0"
for /f "usebackq tokens=*" %%A in ("%FilePath%backup\packs.txt") do (
set /a count+=1
set "url[!count!]=%%A"
)
echo %url[2]%