Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch find folder name inside a directory

Tags:

batch-file

I have a question regarding batch files

So inside this one directory, let's say C:\temp\ I have two items, one is a folder and the other one a text file named "list.txt"

How would I find the name of the folder?

Thanks

like image 341
emochoco Avatar asked Mar 28 '13 14:03

emochoco


2 Answers

If you just want to list subdirectories of the current directory:

dir /ad /b

If you are in another directory you can just do:

dir c:\temp /ad /b

/ad means list all items with attribute "directory", and /b is the bare format

Update:

Like Bill commented below, you can iterate over the output of the dir cmd and set an environment variable. The pitfall here is that if there is more than one subfolder, you won't know which one will be "last". Here is an example that orders the directories by name (/on) and setting the environment variable MY_ENV_VAR to the name of the last subfolder:

for /f "delims=" %%a in ('dir "c:\temp" /on /ad /b') do @set MY_ENV_VAR=%%a

As an aside, if you are going to be doing much more script programming, you might want to invest some time in some PowerShell basics, which gives you much more programmatic control.

Get-ChildItem | where {$_.PSIsContainer}

I find batch scripts to be frustrating to work with after a while.

like image 192
JohnD Avatar answered Oct 04 '22 23:10

JohnD


Try this:

for /d /r "C:\temp" %%i in (*.*) do echo %%~i
like image 45
Endoro Avatar answered Oct 04 '22 23:10

Endoro