Comum
Comum

Reputation: 453

Check if file exists in different directory and respond accordingly

I want to send a undefined number of files to ftp server on a given time of day. After the files are sent I want to save them to another directory and them erase them from the previous directory. Something like this:

ftp -i -s:SendFile.scr serverIp
copy log*.txt C:\Reg\Archives
del log*.txt

This .bat works, however it does not take into account if the file to be copied already exists in the Archives directory, the original is erased and I need it both files to be appended. So, I've written:

ftp -i -s:SendFile.scr 213.13.123.68
IF EXIST C:\Users\Miguel\Archives\tes*.txt
(
    copy /a C:\Users\Miguel\Archives\tes*.txt +  C:\Users\Miguel\tes*.txt  C:\Users\Miguel\Archives\tes*.txt
)
ELSE 
(
    copy tes*.txt  C:\Users\Miguel\Archives
)
del tes*.txt

However this does not work, I've also thought to cd directory and to do it from there but I can't seem to think the proper way to do this. Can anyone help me out?

Upvotes: 0

Views: 96

Answers (1)

Mofi
Mofi

Reputation: 49085

Use this code for appending or just copying the text file depending on existence of the text file with same name in archives directory.

@echo off
for %%I in ("%USERPROFILE%\tes*.txt") do (
    if exist "%USERPROFILE%\Archives\%%~nxI" (
        copy /B "%USERPROFILE%\Archives\%%~nxI" + "%%~I" "%USERPROFILE%\Archives\%%~nxI" >nul
    ) else (
        copy /B "%%~I" "%USERPROFILE%\Archives" >nul
    )
    del /Q "%%~I"
)

The command FOR is used here to process all tes*.txt files in the directory file by file. You can get help on command FOR also be entering for /? or help for in a command prompt window.

%%~I references entire file name with full path of the file to process next without double quotes.

%%~nxI references just file name and file extension without path of the file to process.

/B (binary file) is used instead of /A (ASCII file) to avoid appending ^Z to end of destination file on append. ^Z is a byte with hexadecimal value 1A and means end of file.

Note:

Command copy used to append a file to another file does never check if the existing file ends with a line terminator (carriage return + line-feed) before appending the other file even on usage of /A. So please verify that your tes*.txt files always end with a line terminator as otherwise it could happen that last line of existing file in archives directory is merged together with first line of the source file on append.

Example:

%USERPROFILE%\Archives\test2014336.txt ends with No error. and has no line termination at end of file.

%USERPROFILE%\test2014336.txt starts with Results for ... and has no line termination at beginning of file.

The file %USERPROFILE%\Archives\test2014336.txt would contain in this case after append

No error.Results for ...

instead of

No error.
Results for ...

Upvotes: 1

Related Questions