1

Newbie here- I have this terminal script that doesn't seem to work on Windows to search through subdirectories in a directory for all files with a certain extension and move these to a new directory.

find ./ -name '*.xlsx' -exec cp -prv '{}' \Documents\...' ";"

I was wondering if the same thing could be done using a MATLAB or any other way in Windows script. My ultimate goal is to amalgamate the data in all of these xlsx files into one file. Thanks for the help in advance.

  • does it have to be a Matlab script? you can do this easily with cmd.exe – mael' Jun 25 at 20:02
  • @mael' doesn't have to be MATLAB, I was trying to do this using cmd and it wouldn't work. How can I do it? – Mike Fed Jun 25 at 20:03
  • posted answer that should work for you; let me know if you have any issues with it. – mael' Jun 25 at 20:12
  • @mael' just did it and nothing happened - no errors but nothing showed up in the output directory. Are the "< >" necessary when writing the name or just the directory name, sorry I am very new to this. – Mike Fed Jun 25 at 20:17
  • it's no problem - no you don't need the brackets, that was just the way of saying "insert here". your script will look like: for /r "C:\Your\Directory" %A in (*.xlsx) do (move /y "%A" "C:\New\Directory\%~nxA" - i'll edit the answer to make stuff more clear – mael' Jun 25 at 20:19
1

To loop through a directory in cmd.exe:

for /r "C:\Your\Directory" %A in (*.xlsx) do (move /y "%A" "C:\New\Directory\%~nxA")

The /r in FOR loops through all files rooted in the given directory. The /y in move suppresses a prompt that asks you if moving the file is OK. Using quotes around file/directory paths is best practice in case there are spaces. This will loop through subfolders by default.

Reference: FOR Looping commands

If you fancy a batch solution I prefer setting it up with variables like this:

@echo off

set "old=C:\Your\Directory"
set "new=C:\New\Directory"

for /r "%old%" %%A in (*.xlsx) do (
    move /y "%%A" "%new%\%%~nxA"
)

pause

The main difference (in my opinion) comparing batch to plain command-line is that it's a bit easier to tweak when you can just go back and edit a variable without having to potentially change a path multiple times in the same file. Also note that your parameter %A gets changed to %%A in a batch file.

  • for /R also iterates through sub-directories, so there could occur collisions since the move command moves all files into the new root directory and does not regard the old directory hierarchy... – aschipfl Jun 26 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.