I have a list of folders in a directory, i need to copy just all the folder name to a file and the file should be in a single line seperated by delims. can any help me with this in a batch file.
Thanks
In batch you'd do it like this:
@echo off
setlocal EnableDelayedExpansion
for /D %%f in (*.*) do set n=!n!;%%f
if defined n echo %n:~1% > list.txt
endlocal
To recurse into subfolders replace /D
with /R
and *.*
with .
.
for /R %%f in (.) do set n=!n!;%%f
By adding qualifiers to the loop variable you can specify if you want just the name of the folder (%%~nxf
) or the full path (%%~dpnxf
).
/D
for directory enumeration. It's fixed now in my answer.
Sep 15, 2012 at 22:51
There is not single batch file command that does what you want, but you could use a batch file to accomplish the task and call
it from your own. Ansgar Wiechers' answer had the right basic idea (I see he's fixed his version after I posted mine).
Anyway, here's a version that will produce a semicolon delimited list of first level subfolders in either the current directory or one passed to it as an argument. I chose to use a semicolon delimiter rather than, say, a comma, because it could never be part a valid filename (and commas can be, although it's uncommon).
If a given folder name has spaces in it, it must be quoted it like this (otherwise quoting the folder's directory path is optional):
subdirs "C:\Documents and Settings"
Note it only prints the list to the console (stdout), so if you want to save that in a file, you'll need append a > filename.ext
after the script file name (and any folder name) to redirect the output into file of your choice:
subdirs C:\Windows > dirlist.txt
== subdirs.bat ==
@echo off
setlocal EnableDelayedExpansion
pushd %1
for /D %%d in (*.*) do set n=!n!;%%d
if defined n echo %n:~1%
popd
endlocal
If you'd like to produce the full path to each folder name, you can change the set n=!n!;%%d
to set n=!n!;%%~fd
in the for
loop line.
cd
into the root directory than to prepend the pattern with a path: if "%1" neq "" cd "%1"
Sep 15, 2012 at 22:59
-n
option that suppresses the trailing newline.