How to Read a File Into a Variable in Batch Script

MD Aminul Islam Feb 02, 2024
  1. Use the FOR Loop to Read a File in a Variable in Batch
  2. Example of Taking a File Content in a Variable in Batch
How to Read a File Into a Variable in Batch Script

Sometimes, we need to take the full content of a file in a variable for various purposes like finding specific data from a file, replacing the particular parts of the file, and more. In Batch, taking the entire file content in a variable is very easy.

This article will show us how we can take the whole file content in a variable, and also, we will see an example and explanations to make the topic easier.

Use the FOR Loop to Read a File in a Variable in Batch

For this purpose, we will be using the FOR loop in Batch. The general syntax will be as follows,

FOR /F "tokens=* delims=" %%VAR in (YOUR_FILE.txt) DO echo %%VAR

Let’s see an example regarding the topic.

Example of Taking a File Content in a Variable in Batch

This example will demonstrate how to take the file content in a variable using a simple one-line Batch code. But before we start, suppose we have a text file with the below content:

DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.

Now to read the file above in a variable, the command in Batch will look like the below:

@echo off
FOR /F "tokens=* delims=" %%R in (Mytext.txt) DO echo %%R
pause

After you run the above command, you will get the below output in your console:

DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.
DelftStack is a perfect platform for learning.

Please note that you must run the command where the file is. So if you are not in that location, you must go to that location using the CD command.

Note: The code we provided in this article is written in Batch and only for the Windows CMD.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Batch Variable