Search code examples
if-statementfor-loopcmdxcopy

Using if else in for body CMD


Program have 2 argument 1-folder name 2- file name and if 2- argument equal to txt file name in current directory echo message else copy all txt files to folder given as first argument

This how i try

@echo off
FOR %%f in (*.txt) do  ( IF %%f==%2  ( ECHO PARAM 2 IS NOT COPIED ) ELSE  xcopy %%f "%1\"  )
)
FOR %%f in ("%1\*.txt") do echo %%f>>"%1\logcopy.txt"

in result program cout message and copy all files to folder


Solution

  • for %%f in (*.txt) do if /i "%%~ff"=="%~f2" ( 
        echo "%~2" is not copied
    ) else (
        xcopy /i "%%~ff" "%~1\."
    )
    

    for each .txt file (%%f), if its name and extension (%%~nxf) match the second argument (%~2 is the second argument without quotes, if present) echo message, else, xcopy the file (with full path) to the target folder indicated as first argument