Search code examples
batch-filefor-looppathname

Get last part of directory in for loop, using cd, and in one line


I mean to obtain the last part of a full directory path, when it comes from cd, it is used with for, and set all in one line.

When coming from cd, the path is something like C:\a\b\c\d\. The trailing backslash complicates things.

This is ok for one line in the case of a directory with no trailing backslash (i.e., it cannot come from cd).

This is ok for the case of trailing backslash, but not for one line.

The output of

> FOR %%a IN (`cd`) DO echo %%~pa

is \a\b\c\d\ and the output of

> FOR %%a IN (`cd`) DO echo %%~na

is `cd` (I expected an empty string here).

I guess I should combine this with a syntax like set MYDIR1=%MYDIR:~0,-1% and multiple commands in one line like command1 && command 2. The target one liner would be something like

FOR %%a IN (`cd`) DO set MYDIR1=%MYDIR:~0,-1% && echo %%~nMYDIR1

and perhaps using tokens and/or delims but I couldn't make it work.


Solution

  • To retrieve the information for the current folder

    for %%a in (".") do echo %%~nxa
    

    To retrieve the information using a variable with or without an ending backslash

    for %%a in ("%cd%\.") do echo %%~nxa
    

    But note that, in both cases, you don't have a name+extension available for a drive's root folder.