How to safely append a file name to a Windows folder path argument?

后端 未结 3 824
無奈伤痛
無奈伤痛 2020-12-31 21:26

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 21:41

    EDIT - answer changed to address MC ND's comment

    The solution is so simple :-) "%~f1.\file.ext"

    Windows file names cannot end with . or , so all Windows commands simply ignore trailing . and 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"
                 |                        |
       | "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.

提交回复
热议问题