2

I have a batch file that requires the user to enter a file path. Later on in the file I want to isolate just the filename and extention from the path, ie anything after the last '\'.

set FILEPATH=\\srv-01\My Docs\Templates\My SpreadSheet.xls
...
set FILENAME=???

What do i need to set FILENAME to in order for it to equal 'My SpreadSheet.xls'?

Hopefully this is fairly simple to do. Thanks!

user1055650
  • 417
  • 2
  • 8
  • 13
  • see http://stackoverflow.com/questions/3432851/dos-bat-file-equivalent-to-unix-basename-command you'd need `for /F %i in ("c:\foo\bar.txt") do @echo %~nxi` – Harald Brinkhof Jun 19 '12 at 15:41
  • @HaraldBrinkhof: That question is about DOS (Real DOS) and your little code snippet fails for paths with spaces... – Anders Jun 19 '12 at 15:53
  • @user1055650: The tags dos+windows implies Win9x but I assume that you actually mean WinNT+ – Anders Jun 19 '12 at 15:54

1 Answers1

4
@echo off
set FILEPATH=\\srv-01\My Docs\Templates\My SpreadSheet.xls
for /F "delims=" %%A in ("%FILEPATH%") do set "FILEPATH=%%~nxA"
echo.%FILEPATH%
Anders
  • 97,548
  • 12
  • 110
  • 164
  • It's slow because cmd.exe is actually looking for the file on `"\\srv-01\My Docs"`, even though it doesn't really have to (or I'm not sure why it does). I'll bet that you don't really have such a server or file (it's faster if the location exists). – Michael Burr Jun 19 '12 at 15:56
  • Oh that explains it. Thanks for your help there Michael. – user1055650 Jun 19 '12 at 16:05