Skip navigation

JSI Tip 1018. MOVE does not work if target file exists.


The MOVE command moves one or more files from one directory to the target directory. The syntax is:

move <source> <target>

where

<source> specifies the path and name of the file(s) to move.

<target> specifies the path and name to move file(s) to.

After a MOVE statement, the <source> file(s) no longer exists and the <target> file(s) have the same permissions (ACL) as they did in the <source> folder.

When using the MOVE command, you will receive

Cannot create a file when that file already exists.

if any <target> file already exists.

I have scripted MV.BAT to circumvent this problem. The syntax is:

mv <source> <target>

Wildcards (*) are supported. Examples:

mv <Drive:>\SourceFolder\*.log <Drive:>\TargetFolder\*.log
mv <Drive:>\SourceFolder\*.log <Drive:>\TargetFolder\*.txt
mv <Drive:>\SourceFolder\*.log <Drive:>\TargetFolder\*.*
mv <Drive:>\SourceFolder\file*.log <Drive:>\TargetFolder\*.log

MV.bat contains:


@echo off
setlocal
if %2

"" goto syntax set p1=%1 set p2=%2 set p2=%p2:"=% set p2="%p2%" set fp1=%~DP1 set fp2=%~DP2 set f2=%~N2 set x2=%~X2 if "%f2%"

"" set f2=* if "%x2%"

"." set x2=.* set px="%fp2%%f2%%x2%" if /i %p2%

%px% goto same set px="%fp2%%f2%.*" if /i %p2%

%px% set x2=.*&goto same set f2=* :same pushd %fp1% for /f "Tokens=*" %%i in ('dir /b %p1%') do call :movit "%%i" popd endlocal goto end :syntax @echo Syntax - MV <source> <target> endlocal goto end :movit set p2=%fp2%%f2%%x2% if "%f2%"

"*" goto move2 if "%x2%"

".*" set p2=%fp2%%f2%%~X1 :move1 if exist "%p2%" del /q /f "%p2%" move %1 "%p2%" goto end :move2 set p2=%fp2%%~N1%x2% if "%x2%"

".*" set p2=%fp2%%~N1%~X1 goto move1 :end

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish