0

So basically, let's say I have the following folders in a directory:

test_folder_1

test_folder_2

And I also have a text file with the list of all the folders in that directory.

How can I create a script that will create a text file, test.txt, in all the folders in the directory? (test_folder_1 and test_folder_2)?

I tried modifying some code I found online and got this:

for /F "tokens=1 delims=," %%v IN (folderlist.txt) DO echo test>"C:\Users\myname\My Documents\test\"%%v""  

However, running this, I get "Access Denied."
Any idea what went wrong, or alternative ways to do this? Thanks.

Ambushes
  • 53
  • 1
  • 1
  • 9

1 Answers1

0

The command

echo test>"C:\Users\myname\My Documents\test\"%%v""

despite the wrong double quotes around %%v redirects the text test directly to the directory instead of a file test.txt in the directory. Or in other words: The attempt to create a file with name of an already existing directory is denied by Windows and the result is the access denied error message.

The solution for creating a file test.txt with the line test in each directory specified in text file folderlist.txt is:

for /F "tokens=1 delims=," %%v in (folderlist.txt) do echo test>"%USERPROFILE%\My Documents\test\%%v\test.txt"

It is also possible to create a file test.txt with a file size of 0 bytes in all subfolders of the test folder with following command line in the batch file.

for /D %%v in ("%USERPROFILE%\My Documents\test\*") do echo. >nul 2>"%%v\test.txt"

The command FOR returns in this case the subfolder name with full path always without surrounding double quotes even if the folder path contains a space character as it is the case here.

See How to create empty text file from a batch file? and read the Microsoft article about Using command redirection operators for more details.

echo. >nul 2>test.txt results in writing just a new line to STDOUT redirected to device NUL to avoid printing lots of blank lines on batch execution to screen. And to the file text.txt nothing is redirected from STDERR as there is no error message printed by command ECHO resulting in creating an empty test.txt file.

Run in a command prompt window for /? for help on command FOR.

Community
  • 1
  • 1
Mofi
  • 46,139
  • 17
  • 80
  • 143
  • Thank's Mofi. Can i also ask you, why do we use %%v rather than %v? Can one % sign be used in any cases, and if so, what is the difference between the two? – Ambushes Jul 27 '16 at 20:43
  • You use a single % sign when you run the command directly from the command line. Double % signs are used Inside batch files. – Filipus Jul 27 '16 at 21:15