Search code examples
batch-filecmd

CMD script: copy a file and rename it


I have to write a simple CMD script, its task is to copy a file from one folder to another. User have to enter source and destination path and the name of the file. Script has to add "_copy" to the name of copied file. I only know how to add a suffix to the file after file extension but it's not what I need.

I was trying it with %~n1 and %~x1 but it didn't work properly. Can someone help me solve this problem?

@echo off
echo Source path
set /P folder1=
echo File name
set /P file1=
echo Destination path
set /P folder2=

if %folder1% == %folder2% goto path
if exist %folder2%\%file1% goto exist

set file2=%file1%
set "file2=%~dpn1_copy%~x1"

copy %folder1%\%file1% %folder2%\%file2%
goto end

:exist
echo File exist in destination folder
goto end

:path
echo Destination and source paths are the same
goto end

:end

Solution

  • %1 (first argument from input) never get's set, you need to set it. In this case use call to set it.

    @echo off
    set /p "sourcep=Source path: "
    set /p "sourcef=File: "
    set /p "destp=Destination path: "
    if "%sourcep%" == "%destp%" echo source and destination is the same & goto :EOF
    if exist "%destp%\%sourcef%" echo %sourcef% already exists in %destp% & goto :EOF
    call :work "%sourcef%"
    goto :EOF
    :work
    if not exist "%destp%\%~n1_copy%~x1" (
          copy "%~f1" "%destp%\%~n1_copy%~x1"
    ) else (
          echo "%destp%\%~n1_copy%~x1" already exists
    )
    

    You can also use the search/replace method, but that would include either using delayedexpansion or by adding some escaping to your variables:

    @echo off & setlocal enabledelayedexpansion
    
    set /p "sourcep=Source path: "
    set /p "sourcef= File: "
    set /p "destp=Destination path: "
    set "ext=%sourcef:*.=%"
    set "file=!sourcef:.%ext%=!
    if "%sourcep%" == "%destp%" echo source and destination is the same & goto :EOF
    if exist "%destp%\%sourcef%" echo %sourcef% already exists in %destp% & goto :EOF
    if exist "%destp%\%file%_copy.%ext%" echo "%destp%\%file%_copy.%ext%" already exists & goto :EOF
    copy "%sourcep%\%sourcef%" "%destp%\%file%_copy.%ext%"