Link to home
Start Free TrialLog in
Avatar of samiam41
samiam41Flag for United States of America

asked on

Rename file if it exist (batch file)

Hi Experts!  I am putting a script together that will check c:\dir to see if file.txt exists.  If it exists, I'd like to rename the file to .old

How do I write this?  I needed the experts to help with this.

Here is what I have.  It's a work in progress.

if exist  c:\dir\file.txt (
    ren file.old
) else (
    goto :eof
)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of bbao
bbao
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of samiam41

ASKER

Great work experts!

I literally put my head in my hands when I saw the answer.  Rename and then the file.txt and file.old....  Ugh!  So close.

Thank you both for your time and suggestions!  Glad you all figured it out.
Glad to help, samiam41!
Avatar of Bill Prew
Bill Prew

If this is part of a script you will run more than once, you might want to check before renaming to make sure there isn't already a file with that name, and if there is then take appropriate action.  So I might suggest:

set BaseDir=c:\dir
set OldName=file.txt
set NewName=file.old

if exist "%BaseDir%\%OldName%" (
    if not exist "%BaseDir%\%NewName%" (
        ren "%BaseDir%\%OldName%" "%NewName%"
    ) else (
        rem Add logic to handle duplicate file here
    )
) else (
    rem Add logic to handle missing original file here
    goto :eof
)

Open in new window

~bp
a more generalised version in professional coding.
Hot dmn BP!  Impressive work as always.

Thanks for the script option.  Sorry I already closed the question out but I'm going to keep that script.  :)  It looks amazing!
Thanks, hope it is useful.

~bp