Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch File - Get filename from directory and save as variable

Tags:

batch-file

I am trying to read in a directory and get the filename from that directory. I then want to save the filename as a variable and echo that filename out.

Here is the code I am using:

 for /F %%a in ('dir C:\Users\username\Documents\Training\Pentaho\Outputs\BatchFileOutput\ *.csv') do set FileName=%%a
 echo %FileName%

I am getting the following when command prompt runs: "File not found Directory"

Does anyone know how to resolve this or where I'm going wrong?

Thanks

like image 386
Karen Avatar asked Oct 19 '25 12:10

Karen


1 Answers

Safer way of doing the same:

@echo off
setlocal
set "yourDir=C:\Users\username\Documents\Training\Pentaho\Outputs\BatchFileOutput\"
set "yourExt=*.csv"
pushd %yourDir%
for %%a in (%yourExt%) do echo %%a
popd
endlocal

Sets both: Your directory and the extension you are searching for, Changes the directory to the one previously setted possibly including a /drive change and then runs a loop over all files matching your extension and echo them out. To save only the last one you can use:

...do set fileName=%%a
echo %FileName%

Or to use them all within the loop you can use:

@echo off
Setlocal EnableDelayedExpansion
REM Other things done here

do (
REM Do stuff with %%a here
Set filename=%%a
echo !filename!
echo !filename:~0,6!
echo !filename:a=b!
)

If you just want to echo them, you can just go for echo %%a. If you want to do other things like string-substitution or substrings as described in the comments you need DelayedExpansion as shown above. There are a lot of questions on SO as well.

Note that you can get different "parts" of the path of your file. Have a look on this answer I always have a look on as well. Alternatively check the documentation for the for command typing for /? into the command-line.

like image 87
geisterfurz007 Avatar answered Oct 22 '25 09:10

geisterfurz007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!