Batch Extract path and filename from a variable

前端 未结 5 1561
故里飘歌
故里飘歌 2020-11-27 11:18

How can I extract path and filename from a variable?

Setlocal EnableDelayedExpansion
set file=C:\\Users\\l72rugschiri\\Desktop\\fs.cfg

I wa

5条回答
  •  遥遥无期
    2020-11-27 12:03

    You can only extract path and filename from (1) a parameter of the BAT itself %1, or (2) the parameter of a CALL %1 or (3) a local FOR variable %%a.


    in HELP CALL or HELP FOR you may find more detailed information:

    %~1 - expands %1 removing any surrounding quotes (")
    %~f1 - expands %1 to a fully qualified path name
    %~d1 - expands %1 to a drive letter only
    %~p1 - expands %1 to a path only
    %~n1 - expands %1 to a file name only
    %~x1 - expands %1 to a file extension only
    %~s1 - expanded path contains short names only
    %~a1 - expands %1 to file attributes
    %~t1 - expands %1 to date/time of file
    %~z1 - expands %1 to size of file


    And then try the following:

    Either pass the string to be parsed as a parameter to a CALL

    call :setfile ..\Desktop\fs.cfg
    echo %file% = %filepath% + %filename%
    goto :eof
    
    :setfile
    set file=%~f1
    set filepath=%~dp1
    set filename=%~nx1
    goto :eof
    

    or the equivalent, pass the filename as a local FOR variable

    for %%a in (..\Desktop\fs.cfg) do (
        set file=%%~fa
        set filepath=%%~dpa
        set filename=%%~nxa
    )    
    echo %file% = %filepath% + %filename%
    

提交回复
热议问题