Rob
Rob

Reputation: 2362

Execute on every file in a subdirectory, then delete file

I need help creating a batch file that first runs a command on every file in every subdirectory, and then deletes the file that the command was just run on.

For example:

c:\temp\1\file.abc
c:\temp\2\file.abc
c:\temp\2\file2.abc

Would run:
execute_command.exe c:\temp\1\file.abc
del c:\temp\1\file.abc
execute_command.exe c:\temp\2\file.abc
del c:\temp\2\file.abc
execute_command.exe c:\temp\2\file2.abc
del c:\temp\2\file2.abc

Any help would be appreciated. Thanks.

Upvotes: 1

Views: 561

Answers (1)

Kevin
Kevin

Reputation: 8561

From the C:\temp folder in your example, you should be able to just do

for /r %i in (*.abc) do execute_command.exe %i && del %i

The /r switch says "recurse into every subdirectory of the current directory and run this for command", and the && lets you put multiple commands in the do clause.

You can also specify which folder to use as the base for the recursion, so you could do this from anywhere (not just C:\temp) and it would work:

for /r C:\temp %i in (*.abc) do execute_command.exe %i && del %i

As Joey says in the comment, you can replace the && with an & depending on whether you want to delete the file even if execute_command.exe returns an error.

Upvotes: 4

Related Questions