0

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.

2 Answers2

2

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.

MC ND
  • 69,615
  • 8
  • 84
  • 126
1

Just another option using a technique discovered on dostips.com

set "last=%cd:\=" & set "last=%"
echo %last%
Squashman
  • 13,649
  • 5
  • 27
  • 36
  • Split string into substrings based on delimiter by [Sponge Belly/dostips.com](https://www.dostips.com/forum/viewtopic.php?f=3&t=6429) – Io-oI Apr 19 '20 at 01:51