2

I am very new to Command script please help in below question.

I have below for loop which returns the paths of the files available in C:\test folder and its subfolders. I want the directory path from the file path For example.

If for loop returns C:\test\scripts\sample.txt but i want only C:\test\scripts. for this i have written below command to

For /R C:\seq\ %%a IN (*) do (
set filename="%%a"
echo %filename%
)

This is not assigning file path to variable filename so i can get directory path out of it. Please help in getting directory path from file path in batch scripting.

1
  • 3
    Look at for /? especially the ~-modifiers Commented Apr 10, 2017 at 15:04

3 Answers 3

1

To get the path to the parent directory of a file or directory, use the ~dp modifier of for variable references. In case the trailing \ disturbs, you can use another for loop, like below:

for /R "C:\test\scripts" %%I IN ("*.txt") do (
    echo Path to parent with trailing `\`: "%%~dpI"
    echo Path to parent with trailing `\.`: "%%~dpI."
    for /D %%J in ("%%~dpI.") do (
        echo Pure path to parent: "%%~fJ"
    )
)

Let me recommend to not remove the trailing backslash by sub-string expansion (which you need delayed expansion for when doing it within the loop, as others already said), because there might be situations where the resulting path does no longer point to the original location. For instance, a path D:\ points to the root directory of drive D:; after removing the \, the path is D:, which points to the current directory of the drive. Using the above technique avoids such problems.

Sign up to request clarification or add additional context in comments.

Comments

0

You just need to use the dp modifier:

set filename=%%~dpa

Also, to echo the variable, you'll need to expand it with delayed expansion:

setlocal enabledelayedexpansion
For /R C:\seq\ %%a IN (*) do (
set filename="%%a"
echo !filename!
)

Comments

0
For /R C:\seq\ %%a IN (*) do (
set filename="%%~dpa"
call echo %%filename:~0,-1%%
)

Please see many SO articles about delayed expansion for other ways to show filename.

The ~dp assigns the drive and path of %%a.

see for /?|more from the prompt for information

The :~0,-1 in the echo selects all characters bar the final one

see set /? from the prompt for documentation

Comments

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.