Sunday, December 14, 2008

Recipe - Do Something To Each File In Directory

This one is a real life-saver!

To do the same operation on each file, in Windows, you can use the for command.
for /F %i in ('dir *.dbg /s/b ') do @del %i

The above example deletes all *.dbg files under the current directory

Explanation
for /F %i ......... for each %i
in('dir *.dbg /s/b ') ..... in the list returned by the command. dir /s specifies a recursive search, /b causes it to to output just a list, without the file details
do @del %i ...... del %i is the command to delete the file. @ suppresses the display of the command

Recipe Syntax
for /F {%var} in ('{list-builder-command}') do {action-command}