Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch copy and rename files

I need to copy some directories from the network to my machine and remove the extension .nary from the files in the copied folders; so a file myFile.doc.nary will become myFile.doc. I've got the following Windows batch file, but don't know how to limit the rename to the two folders if the batch file is run from c:\:

xcopy /s \\some_server\MYFOLDER1 c:\MYFOLDER1\
xcopy /s \\some_server\MYFOLDER2 c:\MYFOLDER2\

for /r %%x in (*.nary) do (
    ren "%%x" *.
    )
pause

How do you limit the rename to those two folders on c:\? Also, is it possible to not run the copies if the folders are already on my machine's c:\? Thank you.

like image 621
Alex Avatar asked Dec 11 '25 06:12

Alex


1 Answers

How do you limit the rename to those two folders on c:\?

Just use for /d to loop through the directories.

Modified batch file:

@echo off
xcopy /s \\some_server\MYFOLDER1 c:\MYFOLDER1\
xcopy /s \\some_server\MYFOLDER2 c:\MYFOLDER2\
for /d %%x in (C:\MYFOLDER1 c:\MYFOLDER2) do (
  ren "%%x\*.nary" *.
  )
pause

Also, is it possible to not run the copies if the folders are already in c:\?

Test if the folder already exists before running the xcopy:

Modified batch file:

@echo off
if not exist C:\MYFOLDER1 echo xcopy /s \\some_server\MYFOLDER1 c:\MYFOLDER1\
if not exist C:\MYFOLDER2 echo xcopy /s \\some_server\MYFOLDER2 c:\MYFOLDER2\
for /d %%x in (C:\MYFOLDER1 c:\MYFOLDER2) do (
  ren "%%x\*.nary" *.
  )
pause

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • for /d - Conditionally perform a command on several Directories/Folders.
  • if - Conditionally perform a command.
  • ren - Rename a file or files.
  • xcopy - Copy files and/or directory trees to another folder.
like image 126
DavidPostill Avatar answered Dec 13 '25 01:12

DavidPostill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!