Ragav
Ragav

Reputation: 11

BAT script To perform file compare & based on the result, to run IF or else step

Below are the two files:

A.txt

Ricky
Rose
Charles

PrevA.txt

Ricky
Rose
Charles

When I perform file comparison, after each line of compare, my below code runs for If statement. I need my code to execute either If or else step after full file comparison

Below is my code:

IF EXIST E:\INVdata\A.txt 
(FOR /F "tokens=*" %%a IN (E:\INVdata\A.txt) DO 
(FOR /F "tokens=*" %%b IN (E:\INVdata\PrevA.txt) DO 
(IF %%a==%%b  
(DEL /Q E:\INVdata\A.txt) 
ELSE
(COPY E:\INVdata\A.txt 
 E:\INVdata\PrevA.txt)))) 

Upvotes: 0

Views: 112

Answers (3)

dbenham
dbenham

Reputation: 130879

If you want to check if files are identical, then use a command that is designed to look for differences.

FC will return success if the files match, and error if there is a difference.

@echo off
pushd E:\INVdata
if exist A.txt fc A.txt PrevA.txt >nul && del A.txt || copy A.txt PrevA.txt
popd

Given that you delete A.txt if it is the same as PrevA.txt, then I suspect you also want to delete A.txt after you copy it when it differes from PrevA.txt. You can do that with one operation using MOVE instead of COPY.

@echo off
pushd E:\INVdata
if exist A.txt fc A.txt PrevA.txt >nul && del A.txt || move /y A.txt PrevA.txt
popd

You also might want to use the /B switch with FC, which will cause it to do a binary comparison.

Upvotes: 1

user6811411
user6811411

Reputation:

Ragav you might be better off comparing the contents of the files in way similar to linux diff. With findstr.exe /? See the following examples:

See content of both files

type *A.txt

PrevA.txt


Ricky
old
Rose
Old
Charles

A.txt


Ricky
newa
Rose
NewB
Charles

See lines which are in both files

> findstr /i /G:A.txt PrevA.txt
Ricky
Rose
Charles

See lines only in PrevA.txt

> findstr /i /V /G:A.txt PrevA.txt
old
Old

See lines only in A.txt

> findstr /i /V /G:PrevA.txt A.txt
newa
NewB

Upvotes: 0

Compo
Compo

Reputation: 38654

Without changing anything here it is formatted in such a way as you can understand the correct use of parentheses:

IF EXIST E:\INVdata\A.txt (
    FOR /F "tokens=*" %%a IN (E:\INVdata\A.txt) DO (
        FOR /F "tokens=*" %%b IN (E:\INVdata\PrevA.txt) DO (
            IF %%a==%%b (
                DEL /Q E:\INVdata\A.txt
            ) ELSE (
                COPY E:\INVdata\A.txt E:\INVdata\PrevA.txt
            )
        )
    )
)

Upvotes: 0

Related Questions