Copy file to destination folder and keep duplicates

不羁岁月 提交于 2020-05-28 05:30:26

问题


How do I copy a certain file to a destination folder that already has the same file with the same name, keep both files.

For eg. if a.jpg is already present in the destination folder (assume one in number), now there would two files with different names (eg. a.jpg and a(1).jpg


回答1:


We can also use TIMESTAMP:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%-%MS%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
Xcopy /s "D:\folder1\test.xls" "D:\folder2\test_%fullstamp%.xls"
pause



回答2:


Here's the solution which every one wanted but only few will get (precisely those which looked up this page). @Hackoo I kiss your feet.

Create a batch file named easycopy.bat then put the following in it:

@rem easycopy
@rem Usage: easycopy SourcePath TargetPath (SourcePath can be the path to a directory or a single file)
@rem release 24/05/2020
@echo off

setlocal enableDelayedExpansion

rem Initialize and validate arguments
if "%~2" equ "" echo Error: Insufficient arguments>&2&exit /b 1
set "source=%1"
set "target=%2"
set /a counter=0
if not exist %target%\ echo Error: Target folder %target% does not exist>&2&exit /b 1

if not exist %source%\ call :newfile %source% %target% & set /a counter+=1 & goto :end

rem Do the work
for /r %source% %%F in (*) do if "%%~dpF" neq %target%\ (
  if exist %target%\"%%~nxF" (
    call :newfile "%%F" %target% & set /a counter+=1
  ) else copy "%%F" %target% >nul & set /a counter+=1
)

:end
echo.
if %errorlevel% EQU 0 echo %counter% file/s was/were copied.
if %errorlevel% GTR 0 echo Check if something went wrong.
goto :eof

:newfile <Source> <Destination>
set Source=%1
set Destination=%2
set Filename=%~n1
set Extention=%~x1
set a=1
:loop
if not exist %Destination%\"%Filename%%Extention%" copy %Source% %Destination%\"%Filename%%Extention%" >nul & goto :eof
if exist %Destination%\"%Filename%(%a%)%Extention%" set /a a+=1 && goto :loop
copy %Source% %Destination%\"%Filename%(%a%)%Extention%" >nul


来源:https://stackoverflow.com/questions/46397166/copy-file-to-destination-folder-and-keep-duplicates

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