2013-10-31 48 views
2

我想要一個腳本,以便我的文件從一個文件夾移動到另一個文件夾,並創建一個新文件(如果有任何文件已存在)。批處理腳本移動文件而不覆蓋

例如,我在Downloads文件夾中有一個文件test.csv。當我運行下面的腳本時,如果覆蓋文件,如果在downloads1文件夾中存在具有相同名稱的任何文件。

但我想,它不應該覆蓋現有的文件,但兩個文件應該在那裏..可能是它改變了name.adds 1,2後面。

move C:\user\Downloads\*.csv C:\user\downloads1\ 

另外我知道使用/ -Y會問我需要重寫。但我想自動執行此操作。

move /-Y C:\user\Downloads\*.csv C:\user\downloads1\ 

回答

3

最簡單的方法:

echo No|move /-Y .\file1 .\file2 

您可以使用通配符也:

echo NO|move /-Y "C:\user\Downloads\*.csv" "C:\user\downloads1\" 

而且你的情況:

for %%f in ("C:\user\Downloads\*.csv") do (
    echo No|move /-Y "%%~dpfnxf" "C:\user\downloads1\" 
) 

編輯:

for %%f in ("C:\user\Downloads\*.csv") do (
    if exist "C:\user\downloads1\%%~nxf" (
     rem move "C:\user\downloads1\%%~nxf" "C:\user\downloads1\%%~nxf.bkp" 
     move "C:\user\downloads1\%%~nxf" "C:\user\downloads1\%%~nf-%%N.%%~xf" 
) 
    move /Y "%%~dpfnxf" "C:\user\downloads1\" 
) 

檢查也這樣:Copy files without overwrite

還有一個編輯:

setlocal enableDelayedExpansion 
for %%f in ("C:\user\Downloads\*.csv") do (
    set "moved=" 
    if exist "C:\user\downloads1\%%~nxf" (
    for /l %%N in (1,1,50) do (
    if not defined moved if not exist "C:\user\downloads1\%%~nxf.%%N" (
     move "C:\user\downloads1\%%~nxf" "C:\user\downloads1\%%~nxf.%%N" 
     set moved=yes 
    ) 
    ) 

) 
    move /Y "%%~dpfnxf" "C:\user\downloads1\" 
) 
endlocal 

未經測試。

1

您可以移動第一個不存在的文件,然後重命名源目錄中的剩餘文件,然後複製到目標。

@echo off 
    setlocal enableextensions enabledelayedexpansion 

    rem configure directories 
    set "source=c:\user\Downloads" 
    set "target=c:\user\Downloads1" 

    rem move non existing files to target 
    call :doMove  

    rem if we still have files 
    if exist "%source%\*.csv" (

     rem generate a timestamp 
     set timestamp=_%date:/=%_%time::=% 
     set timestamp=!timestamp:,=! 

     rem rename the remaining files with timestamp 
     ren "%source%\*.csv" "*.!timestamp!.csv" 

     rem and move the remainig files to target 
     call :doMove 
    ) 

    endlocal 
    exit /b 

:doMove 
    robocopy "%source%" "%target%" "*.csv" /fp /njh /njs /ndl /xc /xn /xo /xx /mov 
    goto :EOF 
+0

非常感謝你..很好的解決方案.. :) :) – user2034816