41

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,436
  • 16
  • 61
  • 95

3 Answers3

69

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
  • 127,446
  • 28
  • 251
  • 390
  • 1
    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
  • 4
    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
27

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
  • 14,209
  • 7
  • 52
  • 79
stormofwar
  • 551
  • 5
  • 9
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
  • 11,403
  • 2
  • 35
  • 45