4

Is there a quick way to get the filename and last folder from a full file path (string) in Windows 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.

2
  • If you have a solution, it should go in the answer section. Commented Feb 20, 2013 at 3:06
  • @Casey The solution is in the accepted answer, I just elaborated on it Commented Feb 21, 2013 at 12:51

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Indeed, much more helpful. Thanks!
Here is another link to have under your pillow when writing these ugly dos code: computerhope.com/msdos.htm, see the section on the SET command for info on how I used it in line #3
Great! Fore future reference, I found http://ss64.com/nt/ to be helpful as well.
4

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.