0

I have 2 text files in below format

field1                         : test1
field2                         : test2
field3                         : test3
field4                         : test4

and File 2 as :--

 field1 : test1
 field2 : test2
 field3 : test3
 field4 : test4

I am trying to compare the files and output as "All records Matched" if everything matches and if it doesn't then "Data Mismatch for field name "

I tried using diff to do basic match by ignoring white space but it is not happening.

diff -byw 1.txt 2.txt

Can someone help me with same ?

Regards.

3
  • What does "it is not happening" mean exactly? What is the output of diff? Have you tried -b? Commented Nov 30, 2017 at 8:47
  • yes I tried -b . It shows all lines as mismatch Commented Nov 30, 2017 at 8:50
  • try -E ignore the tab expansion. Commented Nov 30, 2017 at 9:00

2 Answers 2

2

In shell, you can use $? to check output status of previous command. $? holds 0 if last command was successful with exit status 0, other wise. You can check $? value and print statements accordingly. Input files

cat 1.txt 
field1                         : test1
field2                         : test2
field3                         : test3
field4                         : test4
cat 2.txt 
field1 : test1
field2 : test2
field3 : test3
field4 : test4

Commands below

   > diff -bE 1.txt 2.txt 
   > if [ $? -eq 0 ];then echo SUCCESSFUL; else echo FAIL; fi

Output

SUCCESSFUL

If files data do not match [Leading spaces in 2.txt]

diff -bE 1.txt 2.txt 
1c1
< field1                         : test1
---
>  field1 : test1
3c3
< field3                         : test3
---
>  field3 : test3

if [ $? -eq 0 ];then echo SUCCESSFUL; else echo FAIL; fi

OutPut

FAIL
Sign up to request clarification or add additional context in comments.

Comments

1

You are having mismatch as there is space at start of each line in 2nd file. Remove the space using sed

 sed -i 's/^ *//' 2.txt

and now compare using diff -b it will work fine.

1 Comment

Thank you :) .. it worked . Can you tell me how to print sucess or failure based in exact match

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.