问题
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"
/scopies folders and subfolders/ucopies only file that pre-exist in both folders/ysuppresses prompts on overwriting files/itells xcopy that destination is a folder/rignoresREADONLYattribute just in case (this is optional)/ccontinues 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 existchecks if a file exists- the path it checks is composed from
folderApath and name and extension of the file found infolderB
- the path it checks is composed from
copy /ycopies file overwriting existing one- from original file found in
folderB - to similar-named file found in
folderA
- from original file found in
%%~dpnxa syntax goes like this:
%%SOMETHINGameans this is a for-loop variable~suppresses double quotes around file names (we will provide our own ones)dis for disk (c:)pis for path to containing folder (\folderA\)nis for name of the file (i.e.readme)xis 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