I have a directory which I'd like to output the subfolder names (ex: "folder_1" "folder2" "folder 3") enclosed in single quotes and followed by a comma each, into a txt file.
Based off the solution @ How to concatenate strings in a Windows batch file? I managed to come up with the below batch file:
@echo off
set myvar='
for /f %%i in ('dir /b /o:n /ad') DO call :concat %%i
echo %myvar% >>test.txt
goto :eof
:concat
set myvar=%myvar%%1',
goto :eof
which produces a .txt file containing the output:
'folder_1', folder2', folder',
How can I get the output to look more like this:
'folder_1',
'folder2',
'folder 3'
--Need each subfolder name (incl space/s) enclosed in single quotes followed by comma. If possible, I'd also like each folder on a separate line and no comma on the very last folder.
To deal with the missing characters, you are missing one thing from your for
statement.
for /f "tokens=*" %%i in ('dir /b /o:n /ad') DO call :concat %%i
The "tokens=*"
part tells for
to treat the entire line as one variable. By default, for
will split each line into separate variables on spaces, which results in you only getting the first word of each line
To fix the single-line issue, you will need to issue multiple echo
statements. Right now, your code is collecting everything into one variable and then echoing it as a single line. Instead, you can append one line to the file each time through the loop, by moving the echo into your :concat
subroutine.
for /f "tokens=*" %%i in ('dir /b /o:n /ad') DO call :concat %%i
goto :eof
:concat
echo '%*', >>test.txt
goto :eof
In the echo
line, %*
means "all of the arguments". You can't use %1
here because, again, CMD splits arguments on spaces. To learn more about CMD arguments, see http://ss64.com/nt/syntax-args.html
Another way to preserve the spaces is to put quotes around the variable in call :concat "%%i"
, which prevents CMD from splitting the argument. In the subfunction, you then use %~1
instead of %*
.