Vairis
Vairis

Reputation: 227

Batch - How to rename and move file, if file already exists

Good day!

So, my problem is, I am making script, that will move Archives from one folder to another. Problem is, IF archive already exists, then Archive from second folder will be replaced.

These ar Backup Archives, and I want to create backups on any given date.

Here is what I have so far:

set year=%DATE:~6,4%

if not exist "V:\01_%YEAR%" mkdir "V:\01_%YEAR%"  - Creates folder 01_2016
for /d %%X in (01_%YEAR%) do "C:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X\" - Archivates folder
MOVE "V:\01_%YEAR%.7z" "Z:\"  - moves Archive.

Now, idea is, that I write simple If exists code, that will rename Archive that I want to send, to something like this - 01_%YEAR%(1) and then send to folder.

Here is what I came up with:

if exist "Z:\01_%YEAR%.7z" (
ren V:\01_%YEAR%.7z 01_%YEAR%(1).7z
)

Ofcourse my idea is completely wrong, becouse next time I will run this script, archive will be replaced any way.

So, my question is, how can I improve my code?

Regards

Upvotes: 0

Views: 4277

Answers (1)

elzooilogico
elzooilogico

Reputation: 1705

This may help...

you need

setlocal enabledelayedexpansion

replace

MOVE "V:\01_%YEAR%.7z" "Z:\"

by

set "last=0"
set "filename=Z:\01_%YEAR%.7z"

if exist "Z:\01_%YEAR%.7z" (
    for /R %%i in ("Z:\01_%YEAR%(*).7z") do (
       for /F "tokens=2 delims=(^)" %%a in ("%%i") do if %%a GTR !last! set "last=%%a"
    )
    set/a last+=1
    set "filename=Z:\01_%YEAR%(!last!).7z"    
)    

MOVE "V:\01_%YEAR%.7z" "%filename%"

EDIT: brief explanation

First, we set the desired destination filename Z:\01_%YEAR%.7z.

Then we check if file already exist. If it doesn't, we skip the block so move will use the content of filename, that is untouched Z:\01_%YEAR%.7z.

But if file exist, we enter the block.

The first for checks for all ocurrences of the pattern Z:\01_%YEAR%(*).7z where * may be anything.

Again, if there isn't any match, we jump to set/a last+=1 (before last=0, now last=1), so filename now will be Z:\01_%YEAR%(1).7z

If there is any match, the second for will be executed. Here the result of the first block is scanned, and the part between parentheses extracted. So it may be 1,2,3,... from previous executions. Once, there aren't more matches we reach the set/a last+=1 line, but now (i.e from previous) as last=1, after set/a last+=1, last=2, so filename now will be Z:\01_%YEAR%(2).7z

So each time the (*) part in incremented by one.

Note: this is not perfect code, as the * in for /R may return strings, but is a good starting point.

Type for /? for more details

Hope it helps

Upvotes: 1

Related Questions