Discussion forum for all Windows batch related topics.
Moderator: DosItHelp
-
Gunner
- Posts: 7
- Joined: 13 Dec 2019 02:40
#1
Post
by Gunner » 16 Dec 2019 05:18
Hi
Within my .bat file I want to get the name of the only file in a folder (I am guaranteed that there will only ever be 1 file)
I have tried this
Code: Select all
set fn="a"
for /r %%i in (*) do set %fn% = %%~nxi
but fn is not set as expected
First question: why not and how can I fix
Second question : this seems a clunky solution - is there a better way
-
aGerman
- Expert
- Posts: 4678
- Joined: 22 Jan 2010 18:01
- Location: Germany
#2
Post
by aGerman » 16 Dec 2019 05:34
Code: Select all
for /r %%i in (*) do set "fn=%%~nxi"
No need to define variable fn beforehand. Using %fn% in the assignment is probably not what you wanted, use the variable name instead of the variable value. Omit the spaces around the equal sign because they would lead to variable names having a space appended and its value having a space prepended. Surrounding quotation marks in the assignment will protect you from problems with special characters such like & in a file name.
If you don't have to search recursively in subfolders you don't need option /r and you don't need the ~nx modifier to remove the path. And note that you will always find your own batch file the way the code is currently written, because you didn't specify a different path where to search files.
Steffen
-
Gunner
- Posts: 7
- Joined: 13 Dec 2019 02:40
#3
Post
by Gunner » 16 Dec 2019 07:27
Thanks for the reply and explanation - all working nowq