Concatenate all filenames inside a folder in a variable within a Batch script



As an IT Administrator, it is often necessary to perform operations on the contents of a folder in a batch script. One such operation is the need to concatenate all the filenames within a folder into a single variable. This article will explain how to do this in a batch script.

The first step is to create a batch script. This can be done in any text editor, such as Notepad or WordPad. The following is an example of a batch script that will concatenate all the filenames in a folder into a single variable:

@echo off

rem List all the files in a folder
for /f \tokens=*\ %%F in ('dir /b') do (
\trem Echo each filename to a single variable
\tset FILES=%FILES% %%F
)

rem Echo the variable
echo %FILES%

This script will list all the files in a folder and then echo each filename to a single variable. The last line of the script will then echo the contents of the variable, which will be a list of all the filenames in the folder.

If you wish to perform further operations on the contents of the variable, such as sorting or filtering, you can do so by adding additional code to the batch script. For example, if you wanted to sort the list of filenames in alphabetical order, you could add the following code to the script:

@echo off

rem List all the files in a folder
for /f \tokens=*\ %%F in ('dir /b') do (
\trem Echo each filename to a single variable
\tset FILES=%FILES% %%F
)

rem Sort the list of filenames
set FILES=%FILES:~1%
for /f \tokens=* delims=\ %%G in ('echo %FILES%^|sort') do (
\tset FILES=%%G
)

rem Echo the variable
echo %FILES%

This code will sort the list of filenames in alphabetical order and then echo the contents of the variable.

In conclusion, this article has explained how to concatenate all the filenames within a folder into a single variable in a batch script. Further operations can be performed on the contents of the variable by adding additional code to the batch script.

Inquire Now

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Find your next full or part-time role here

ScaleDesk can either help you find your next full time gig or a part time side gig where you can create extra income!

Onboard with us once
Skip HR screening and go to the final interview with with only your resume and a video interview you never have to redo
Get paid electronically every month for the hours you work
We will be your reference even if you work for us once

IT Teams: Use ScaleDesk to augment your team

Schedule Demo