0

I'm trying to run a command on all files within a directory (and its child directories) but am struggling to generate a relative path for the files I find.

The code I have is...

@echo off

set currentDir=%~dp0

for /r %%f in (*.js) do (
    echo %currentDir%
    echo %%f

    set relativePath=%%%f:%currentDir%=%
    echo %relativePath%
)

Basically if I run the script in C:\somedir and it finds C:\somedir\anotherdir\file.js I need %relativePath% to contain only anotherdir\file.js

Please help!

1 Answer 1

2

EDITED - to adapt to required output.

 @echo off

    setlocal enableextensions enabledelayedexpansion

    rem to take batch file directory as current directory
    set "currentDir=%~dp0"

    rem OR to take current directory as current directory
    set "currentDir=%cd%"

    rem Select only one of the above

    rem add trailing backslash if not present
    if not "%currentDir:~-1%"=="\" set "currentDir=%currentDir%\"

    rem Do recurse directory
    for /r %%f in (*.js) do (
        set "relativePath=%%f"
        set "relativePath=!relativepath:%currentDir%=!"
        echo %relativePath%
    )
Sign up to request clarification or add additional context in comments.

2 Comments

+1, but I love the endlocals when setlocal is used :-).It's more neat.
@npocmaka : I agree. I've not included it thinking batch file will need more content. Anyway, endlocal is implicit and at end of batch file execution, any pending setlocal is canceled. It's only mandatory if you need to ensure, after a setlocal has been emited, that changes to environment variables persist. BUT, yes, i prefer balanced code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.