Reputation: 1
I want to copy a file to the first subdirectory of a folder.
Example:
\---main_folder
|
\---subfolder *(copy here)*
|
\---sub_subfolder *(do NOT copy here)*
I know it is quite easy to copy a file to a directory and it's subdirectories, e.g:
for /r "G:\main_folder" %%i in (.) do @copy "G:\abc.txt" "%%i"
But this code copies the file to ALL subdirectories of main_folder
, whereas I wish only to copy to subfolder
(See my rudimentary example).
I checked the help on for
, (for /?
), but couldn't figure this out.
Am I missing something?
Upvotes: 0
Views: 98
Reputation: 38579
Because your question asks, 'I want to copy a file to the first subdirectory of a folder.'
, and not, 'I want to copy a file to every top level subdirectory of a folder.'
, which is what the comment, you've agreed works does. You need to first decide on what constitutes first
.
This example uses first
as that which is determined by name sort order (alphabetically).
@For /F Delims^=^ EOL^= %%A In ('Dir /B/AD/ON "G:\main_folder"') Do @Copy /Y "G:\abc.txt" "%%A" & GoTo :EOF
Edit
Because you've now clarified that your question parameters were wrong, not misinterpreted, i.e. 'I want to copy a file to every top level subdirectory of a folder'
then the comment initially provided showed a correct method:
@For /D %%A In ("G:\main_folder\*") Do @If Exist "G:\abc.txt" Copy /Y "G:\abc.txt" "%%A" >Nul 2>&1
Alternatively, should be fractionally quicker, performing the If Exist
first:
@If Exist "G:\abc.txt" For /D %%A In ("G:\main_folder\*") Do @Copy /Y "G:\abc.txt" "%%A" >Nul 2>&1
Upvotes: 0
Reputation: 34899
Since you are using for /R
, your file is going to be copied into every directory in your tree.
Use for /D
instead to iterate throufgh a certain hierarchy level, like in the following example:
for /D %%I in ("G:\main_folder\*") do copy "G:\abc.txt" "%%~I"
This of course copies the file into every immediate sub-directory of G:\main_folder
.
Upvotes: 1