How to Use Batch File to Write to a Text File

MD Aminul Islam Feb 02, 2024
How to Use Batch File to Write to a Text File

Programs can save their data or log in a text file to reuse for next time. This article is for you if you want a solution to writing a text file through your Batch script.

This article will discuss how we can generate a text file through our Batch script. Also, we will see examples and explanations to make the topic easier.

Use Batch File to Write to a Text File

You can put a text on your file using the keyword ECHO. In our below example, we will create a text file and put some text on it.

The code for our example will look like the below.

@ECHO off
ECHO This is a text that is saved as a text file. > "G:\BATCH\Test.txt"

After executing the script, we will get the below texts on the file when we open the text file.

This is a text that is saved as a text file.

Providing the file name with the exact directory is very important. The general format for creating a text file and putting some text on it is ECHO Your Text Here > "D:\YouDirectory\Filename.txt".

Now we successfully created a text file and modified it. Let’s go to a bit advanced example.

If you want to update the recently created file, you can follow the article below. To do this, we first need to read the file and then save this file data in a variable, and lastly, we need to combine that variable data with updated data and save it to the text file.

The code for our example will look like the below.

@ECHO off
FOR /F "tokens=* delims=" %%x IN (Test.txt) DO SET text=%%x
ECHO %text% This is an update. > "G:\BATCH\Test.txt"

If you notice the code deeply, you can see that we used a FOR loop to read the text file. We saved the current data of the text file to a variable named x, and then we created a variable named text and assigned it the value of x.

Lastly, we combined the previous value of the text file and the updated text with the ECHO keyword. Now we saved the whole date to the text file.

After executing the script, we will get the below texts on the file when we open the text file.

This is a text that is saved as a text file. This is an update.
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 File