I would like to achieve list of all directories including sub-directories listed with their relative path eg omitting originating directory form the list tried to count the amount of characters in original path and then subtract those from the fuul name, but I can get over variable replacement..
set "BIN=c:\somedir\"
set x=%BIN%
set /A n=0
setlocal EnableDelayedExpansion
for %%m in (4095 2047 1023 511 255 127 63 31 15 7 3 1 0) do (
if not "!x:~%%m,1!" == "" (
set /a n =%%m 1
set x=!x:~%%m!
set x=!x:~1!
if "!x!" == "" goto done
)
)
:done
set TMP=""
for /f %%i in ('dir /b /ad /s "%BIN%" ') do (
set TMP=!%%i!
echo !%TMP:~%n!
)
where first part counts the length of the path/string - "n" and this then should be used as "shortening" parameter inside other for - !%TMP:~%n! - to cut out the leading part, the input, path, form full path to the files.
any ideas how to achieve it?
CodePudding user response:
If you wanted to do it more efficiently then perhaps something as simple as this will suffice:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "BIN=c:\somedir\"
For /D /R "%BIN%" %%G In (*) Do (Set "_=%%G" & SetLocal EnableDelayedExpansion
For %%H In ("!_:*%BIN%=!") Do EndLocal & Echo %%H)
Pause
And if you also needed all directories, (because a standard for
loop does not grab them all), then perhaps:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "BIN=C:\somedir\"
For /F "Delims=" %%G In ('Dir "%BIN%" /A:D /B /S 2^>NUL') Do (Set "_=%%G"
SetLocal EnableDelayedExpansion & For %%H In ("!_:*%BIN%=!") Do (EndLocal
Echo %%~H))
Pause
If you wanted true RELATIVE paths then change %%~H
to .\%%~H
, and obviously if you wanted those doublequoted, then change it to ".\%%~H"
.
CodePudding user response:
This is definitely not the most efficient way, but certainly the simplest:
@%SystemRoot%\System32\forfiles.exe /S /P "C:\somedir" /C "%SystemRoot%\System32\cmd.exe /D /C \"If @IsDir == TRUE For /F \"Tokens=* Delims=.\\\" %%G In (@RelPath) Do @Echo %%G\"" & Pause
If you really wanted RELATIVE paths however, the following is shorter, and may be more accurate:
@%SystemRoot%\System32\forfiles.exe /S /P "C:\somedir" /C "%SystemRoot%\System32\cmd.exe /D /C \"If @IsDir == TRUE For %%G In (@RelPath) Do @Echo %%~G\"" & Pause
And if you wanted those doublequoted, (as it is best practice), then it should be even shorter and simpler:
@%SystemRoot%\System32\forfiles.exe /S /P "C:\somedir" /C "%SystemRoot%\System32\cmd.exe /D /C \"If @IsDir == TRUE Echo @RelPath\"" & Pause
You could even use lazy, non robust code and make that line even shorter:
@forfiles /S /P "C:\somedir" /C "cmd /C If @IsDir==TRUE Echo @RelPath" & Pause