How to get path relative to the working directory?

坚强是说给别人听的谎言 提交于 2020-01-07 04:59:06

问题


I have a script that recursively loops through all .txt files in the working directory and subdirectories and does something with that files. Now I would like to exclude all files in certain subdirectories that are listed in a exclude.txt file:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

for /r %%f in (*.txt) do (
    CALL:processFile %%f %%~df%%~pf
)
GOTO:EOF

:processFile
    SET file_=%~1
    SET path_=%~2                 <- %%~df%%~pf is the full path :(
    find "!path_!" exclude.txt
    IF !ERRORLEVEL! EQU 1 (
        REM do something here
    )
    GOTO:EOF

However, %%/~df%%~pf expands to the absolute path. How can I get the path relative to the workingdirectory? I want to list only the subdirectories in exclude.txt and not the full paths.

PS: I could of course read the relative paths from exclude.txt, append %cd% and write them to some exclude.temp and then search in this temporary file, but I hope there is a nicer way.


回答1:


Give this a try.

@ECHO OFF
SETLOCAL EnableDelayedExpansion

for /r %%F in (*.txt) do (
    echo %%F|findstr /I /G:exclude.txt >nul 2>&1
    IF NOT "!ERRORLEVEL!"=="0" (
        REM do something here
    )
)



回答2:


Here is a different approach, relying on the fact that xcopy is capable of returning relative paths. Since we do not want to copy anything, the /L switch needs to be used (list but do not copy).

for /F "delims=" %%F in ('
    xcopy /L /I /S ".\*.txt" "%TEMP%" ^| find ".\"
') do (
    echo(Relative path to file: "%%~F"

    rem // This block is only needed in case the leading `.\` disturbs:
    set "FILE=%%~F"
    setlocal EnableDelayedExpansion
    echo(Relative path, no `.\`: "!FILE:*.\=!"
    endlocal
)


来源:https://stackoverflow.com/questions/41746300/how-to-get-path-relative-to-the-working-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!