Parsing a DOS line string: folder and file name in a line

Is there a quick way to get the file name and last folder from the full path of a file (line) on the DOS command line?

I would expect 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 hit my head about this using FOR / F, but since the full path can be any length, I can't figure it out.

Thanks!

+4
source share
3 answers

Try the following:

 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% 

This one is your friend.

+5
source

FOR / TOKENS will work if the path has been canceled, 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 
+4
source

Based on @deStrangis answer, here is the solution I came across:

 @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 
0
source

All Articles