Batch script for copying files based on name

不羁的心 提交于 2019-12-11 07:46:07

问题


Basically I want to write a little batch script that does the following - I have two folders, A and B... A has 10 files and B has 100. I want to compare the names of the files in each folder and if any in B have the same name as in A, then to copy them to folder A and overwrite the original file.

I was trying to start off by doing a "for" command on folder A but then I would have to follow that with an IF to compare the filenames which I have no idea how to express correctly

    for /r "C:\folderA" %%a in (*.filetype) do (...)

Sry but I am useless with batch scripting. I found a couple of threads covering similar questions, but rly didn't follow the answers enough to help.

Is this difficult? The other threads comparing two filenames looked kinda complicated.

Thanks for any help :)


回答1:


Try this:

xcopy /s /u /y /i /r /c "C:\folderB\*.filetype" "C:\folderA"
  • /s copies folders and subfolders
  • /u copies only file that pre-exist in both folders
  • /y suppresses prompts on overwriting files
  • /i tells xcopy that destination is a folder
  • /r ignores READONLY attribute just in case (this is optional)
  • /c continues copying even if errors occur (this is optional)

More information on xcopy can be found here (or xcopy /?)

If that does not work for you then something like this should do:

for /r "C:\folderA" %%a in (*.filetype) do if exist "C:\folderB\%%~nxa" copy /y "C:\folderB\%%~nxa" "C:\folderA\%%~nxa"

Here is what it does:

  • if exist checks if a file exists
    • the path it checks is composed from folderA path and name and extension of the file found in folderB
  • copy /y copies file overwriting existing one
    • from original file found in folderB
    • to similar-named file found in folderA

%%~dpnxa syntax goes like this:

  • %%SOMETHINGa means this is a for-loop variable
  • ~ suppresses double quotes around file names (we will provide our own ones)
  • d is for disk (c:)
  • p is for path to containing folder (\folderA\)
  • n is for name of the file (i.e. readme)
  • x is for extension (i.e. .txt)

You can mix and match those as you like. More info is here or try for /?

If logic needs to be more complicated I suggest either using ( ) brackets + delayed expansion or call :label (call /?)

UPDATE: Corrected mixup of FolderA and FolderB



来源:https://stackoverflow.com/questions/53350200/batch-script-for-copying-files-based-on-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!