Mohammad Reza Rezwani
Mohammad Reza Rezwani

Reputation: 331

How to know upper folder name via cmd

is there any way to know what is the name of upper folder(directory) via cmd in windows? for example you are in C:\A\B\C I need a command which tells B

Upvotes: 0

Views: 663

Answers (2)

aschipfl
aschipfl

Reputation: 34989

Yes, there is -- use for loops:

set "FOLDER=C:\A\B\C"

for %%J in ("%FOLDER%") do for %%I in ("%%~dpJ.") do echo(%%~nxI

The outer loop is needed to go up one level as %%~dpJ expands to C:\A\B\; let us append a . like %%~dpJ. to get C:\A\B\., which is equivalent to C:\A\B; finally, the inner loop is needed to retrieve the pure name of the referenced directory as %%~nxI returns B.


It is also possible using one for loop:

set "FOLDER=C:\A\B\C"

for %%I in ("%FOLDER%\..") do echo(%%~nxI

The .. means one level up, and C:\A\B\C\.. is therefore equivapent to C:\A\B; finally, %%~nxI returns B again.

Upvotes: 2

Compo
Compo

Reputation: 38719

Alternative, using the built in %CD% variable.

From the command prompt:

For %A In ("%CD%\..\.") Do @Echo(%~nxA

From a batch file:

@For %%A In ("%CD%\..\.") Do @(Echo(%%~nxA&Timeout 5 1>Nul)

Upvotes: 2

Related Questions