37

How do I get the filename from this string?

"C:\Documents and Settings\Usuario\Escritorio\hello\test.txt"

output:

"test.txt"

I really tried to find this one before posting, but all the results were contaminated, they talk about getting filenames from current dir (I must work with strings only)

ajax333221
  • 11,086
  • 15
  • 58
  • 93

3 Answers3

64

Method 1

for %%F in ("C:\Documents and Settings\Usuario\Escritorio\hello\test.txt") do echo %%~nxF

Type HELP FOR for more info.

Method 2

call :sub "C:\Documents and Settings\Usuario\Escritorio\hello\test.txt"
exit /b

:sub
echo %~nx1
exit /b

Type HELP CALL for more info.

dbenham
  • 123,415
  • 27
  • 239
  • 376
  • please, can you explain "%~nx1"? – Yukulélé Jun 05 '13 at 10:00
  • @Yukulélé - It modifies the expansion of `%1`, treating it as a file path and expanding to the name and extension, disregarding drive and path. Type `HELP CALL` or `CALL /?` from the command prompt for more information about all of the parameter expansion modifiers. – dbenham Jun 05 '13 at 11:23
  • 3
    thanks, I found more details here http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true – Yukulélé Jun 05 '13 at 14:48
22

if your path comes as a parameter, just use:

%~nx1 (1 is for the first param and we suppose it's the first one)

echo %~nx1 would return directly test.txt

Nae
  • 12,111
  • 5
  • 46
  • 74
stormofwar
  • 503
  • 4
  • 9
  • 1
    I just needed this badly myself and, for that particular case (as parameter), it's much more shorter and elegant. – stormofwar Jan 18 '16 at 12:39
9

Assuming you need the the names of files under the "c:\temp" directory tree (including sub-directories):

FOR /R c:\temp %i in (*.*) do echo %~nxi
Marc
  • 10,725
  • 2
  • 34
  • 41