This works for me, if you put the following in a CMD file:
@echo off SETLOCAL EnableDelayedExpansion for /f "usebackq delims=" %%A in (`cmd /c dir /s /b`) DO ( set NAME=%%A set SHORT=!NAME:%cd%\=! echo.!SHORT! )
It takes the output of your original dir
command and uses string substitution to remove the current directory. See set /?
for more information on this. If you prefer to pass the directory as an argument instead of using the current directory, try this modification of the variables:
@echo off SETLOCAL EnableDelayedExpansion for /f "usebackq delims=" %%A in (`cmd /c dir /s /b %1`) DO ( set NAME=%%A set SHORT=!NAME:%~1\=! echo.!SHORT! )
Beware of filenames and directories which have an exclamation mark in the filename, as they tend to get stripped out with this method. If you need something more robust which can handle this, look into installing GNU sed or grep. You can also investigate using the GNU find command if you don't mind the filenames coming back UNIX style with slashes instead of backslashes, and a leading ./
in front of each entry.
There is also another answer which may give you ideas on handling exclamation marks in CMD processing: https://stackoverflow.com/questions/32873578/how-to-read-a-string-with-from-a-file-in-windows-batch-script/32874195#32874195