Suppose I have a batch script that expects a folder path in argument %1
. I want to append a file name to the path and use that in a command. Is there a simple w
Since ~f eliminates multiple backslashes, I think this works just as well as the original proposal, and also appears to handle share roots and long paths correctly:
for /F "delims=" %%i in (%~f1\file.ext) do set filename=%%~fi
I don't see a way to make it work for all the cases. Your solution will handle all the local paths cases, but to handle UNC or long paths it seems that it is necessary to first correct the path and then append the file data
@echo off
setlocal enableextensions disabledelayedexpansion
for /f "delims=" %%a in ("%~f1."
) do for /f "delims=" %%b in ("%%~fa\file.ext"
) do echo "%%~fb"
This "should" handle local, network or long paths (the reason for the for /f
is the ?
), both absolute and relative, and the posibility of no giving a path in the command line.
EDIT - answer changed to address MC ND's comment
The solution is so simple :-) "%~f1.\file.ext"
Windows file names cannot end with .
or <space>
, so all Windows commands simply ignore trailing .
and <space>
in file/folder names.
And a single .
following a backslash represents the current directory at that location.
Assume the current working directory is c:\test
, then the table below show how various values get resolved:
"%~1" | "%~f1.\file.ext" | equivalent to
-------------+------------------------+------------------------
"c:\folder\" | "c:\folder\.\file.ext" | "c:\folder\file.ext"
| |
"c:\folder" | "c:\folder.\file.ext" | "c:\folder\file.ext"
| |
"c:\" | "c:\.\file.ext" | "c:\file.ext"
| |
"c:" | "c:\test.\file.ext" | "c:\test\file.ext"
| |
"." | "c:\test.\file.ext" | "c:\test\file.ext"
| |
".." | "c:\.\file.ext" | "c:\file.ext"
| |
<no value> | "c:\test.\file.ext" | "c:\test\file.ext" I hadn't thought of this case
until I saw MC ND's answer
You can easily reduce the expression into the canonical equivalent form using a FOR loop:
for %%A in ("%~f1.\file.ext") do echo "%%~fA"
As Harry Johnston states in his comment, this solution does not work with UNC root paths (\\server\shareName
) or long paths (\\?\c:\somePath
). See MC ND's answer if you need to support either of those cases. The Harry Johnston answer is simpler, but it does not support the case of no argument given.