Easily swap file names?

Posted on

QUESTION :

Is there an easy way to swap the file names of two files in Windows? Perhaps using the move command in the shell?
Preferably without using external software.

Example: I have fileA.txt and fileB.txt. After the operation, fileA.txt is now called fileB.txt, and vice versa.

ANSWER :

Simple 3 step process in Windows:

ren a.txt a.tmp
ren b.txt a.txt
ren a.tmp b.txt

You can run this directly or save it to a batch file.

Here is while 3 (three) steps combined into single command line:

@ren a.txt temp.tmp & @ren b.txt a.txt & @ren temp.tmp a.txt

Here is switch-filename.cmd might be usabled:

@echo off
if not "%4"=="" call :help %0
if "%3"=="/?" call :help %0
if "%2"=="/?" call :help %0
if "%1"=="/?" call :help %0
if "%1"=="" call :help %0
if "%1"=="" goto :eof
if "%2"=="" call :help %0
if "%2"=="" goto :eof
setlocal
if "%3"=="" set ch=echo
if "%3"=="#ok#" set ch=
call :v1 %1 %2
endlocal
echo.
echo [%date% %time%] Completed!
goto :eof
:help
echo.
echo Syntax: %1 FullPathFileName01.Ext FileName02.Ext [enter]
echo.
echo         %1 C:WinTempSapGui_v1.txt SapGui_v5.txt [enter]
echo.
echo         %1 \SvrTmpGuiSAP_v0.txt GuiSAP_v9.txt [enter]
echo.
goto :eof
:v0
%ch% ren %1 tmp_%~n1%~x1
%ch% ren %2 %~n1%~x1
%ch% ren %~p1tmp_%~n1%~x1 %~n2%~x2
goto :selesai
:v1
set f01=%1
set f02=%2
echo f01 = %f01%
echo f02 = %f02%
%ch% ren %1 tmp_%~n1%~x1
if "%f01:~0,2%"=="\" (
  %ch% ren \%~p1%2 %~n1%~x1
  %ch% ren \%~p1tmp_%~n1%~x1 %~n2%~x2
) else (
  %ch% ren %~p1%2 %~n1%~x1
  %ch% ren %~p1tmp_%~n1%~x1 %~n2%~x2
)
echo.
echo f01 = %f01%
echo       %f01:~0,2%
echo f02 = %f02%
echo       %f02:~0,2%
set f01=
set f02=
goto :eof

Any idea for improvement are welcome. 🙂