Creating a txt file for certain type of files using batch

Posted on


I have a folder containing all types of files. Let’s say my folder path is E:/temp.

I would like to create, only for the .avi type files, a txt file and name the txt file as the name of the movie. so if I have 20 clip .avi files in the folder, I want to open 20 txt file, and each txt file will be named after a clip.

Also, inside the txt file I need to write (for all txt file it will be the same) the word “HAPPY”

What will be the script using batch file?


You need to use FOR to iterate over the elements you want to work with. See How to loop through files matching wildcard in batch file for details.

Once you have that part solved, you’ll want to create the filename of your .txt file. The command line documentation of FOR can help us here:

In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only

The last entry is what we want. We want to cut off the .avi, so we use ~n in our variable to get only the name. This is where the %%~nf.txt comes from.

We start with %%f, the current filename. Then we cut off the extension with %%~nf and tack on the .txt… Done: %%~nf.txt

The last problem is when you try to solve it all on one line, like:

FOR %%f IN (*.avi) DO ECHO HAPPY > %%~nf.txt

That wouldn’t work, because the shell will interpret the > and start outputting to that file instantly, which is not what we want. We want the ECHO to be processed for every single file, so I simply split it into multiple lines.


REM Iterate over all *.avi file in the current directory
FOR %%f IN (*.avi) DO (
    REM Cut off the extension from %%f, tack on .txt and 
    REM use it as the filename for our HAPPY output
    ECHO HAPPY > %%~nf.txt

Create a text file named happy.txt containing “HAPPY“. Create a batch file named makehappy.cmd containing this:

for %%i in (*.avi) do copy happy.txt "%%i.txt"

Run makehappy. The new text files will have a double extension, but there are ways around that if necessary.

Leave a Reply

Your email address will not be published.