Is there a quick way to get the filename and last folder from a full file path (string) in Wind开发者_JAVA百科ows command line?
I would expect for input -> results:
"c:\test\1\2\test.txt" -> "2", "test.txt"
"c:\test\1\2\3\a.txt" -> "3", "a.txt"
"c:\test\0\b.txt" -> "0", "b.txt"
"c:\c.txt" -> "", "c.txt"
I've been banging my head at this using FOR /F but since the full path can be any length, I can't figure it out.
Try this:
for %I in (c:\test\1\2\3\a.txt) do set path=%~pI
for %I in (c:\test\1\2\3\a.txt) do set file=%~nxI
set pth2=%path:~0,-1%
for %I in (%pth2%) do set lastdir=%~nxI
echo %file% %lastdir%
The Windows Command Line Reference is your friend.
FOR/TOKENS would work if the path were reversed so what about;
echo off
set apath=c:\test\1\2\3\a.txt
call :reverse "%apath%"
for /f "tokens=1,2 delims=\\" %%a in ("%reverse.result%") do set afile=%%a&set adir=%%b
call :reverse "%apath%"
set apath = %reverse.result%
call :reverse "%afile%"
set afile= %reverse.result%
rem handle no dir;
if "%adir:~0,1%"==":" set adir=
echo File: %afile%
echo Dir: %adir%
goto:eof
:reverse
set reverse.tmp=%~1
set reverse.result=
:reverse.loop
set reverse.result=%reverse.tmp:~0,1%%reverse.Result%
set reverse.tmp=%reverse.tmp:~1,999%
if not "%reverse.tmp%"=="" goto:reverse.loop
goto:eof
eof:
For
File: a.txt
Dir: 3
Based on @deStrangis' answer, here's the solution I came up with:
@ECHO OFF
SETLOCAL
CALL :get_path "C:\test\1\2\3\a.txt"
GOTO last
:get_path
:: get file path
SET _path=%~p1
:: get file name and extension
SET _name=%~nx1
:: remove trailing backslash from path
SET _path=%_path:~0,-1%
:: trim path
CALL :trim_path %_path%
:: output
ECHO %_path% %_name%
GOTO :eof
:trim_path
:: get file name from a path returns the last folder
SET _path=%~n1
GOTO :eof
:last
ECHO ON
精彩评论