samiam41
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.
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
)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Glad to help, samiam41!
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
)
~bp
a more generalised version in professional coding.
ASKER
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 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
~bp
ASKER
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.