The other day I wanted to change CSV files TXT files for some reason. The weird part was that they were in spread out in a directory tree, and that I also wished to preserve the directory structure.
WHAM
for /r c:\SOURCE %i in (*.csv) do mkdir "c:\DESTINATION%~pi"& move "%~fi" "c:\DESTINATION%~pi%~ni.txt"
Because I am wishing to create a mirror of my original directory tree (and not do a in-place upgrade), the easiest way to do it was have a SOURCE tree, and a DESTINATION tree, so replace these variables in the command above.
What this loop is doing is searching through the tree for any files of a CSV extension. When it finds one, it will create the path in the DESTINATION tree, and then move the file into the corresponding folder, stripping the CSV extension and appending the TXT extension.
As a side note, it is interesting that as a default in Windows mkdir will automatically create intermediate directories if they do not exist. This is different from Linux, in which you need to append a -p switch to make it so. You can turn on command extensions as they are called, by running cmd /e:on or off with cmd /e:off in Windows when launching your shell.
In this Recursive for loop I am taking advantage of special FOR variables to make my substitutions. For a full list, check 'for /?'. I recommend doing so, it is full of useful hacks you can do to make an ordinary loop extremely powerful.
%~pi stands for Path Only
%~fi stands for Fully Qualified Path Name
%~ni stands for Name Only
Luckily I did not care about any other files that were not CSV's in this structure. If I had, I would have probably re-run the loop, changing out CSV for the target extension, and doing a simple move, instead of stripping the iterator's value to the path minus then extension and tacking on the extension.
Like so
for /r c:\SOURCE %i in (*.doc) do mkdir c:\DESTINATION\%pi"& move "%~fi" "c:\DESTINATION%~pi%~nxi
%~nxi stands for Name with Extension
No comments:
Post a Comment