I have two files , say a & b. I want to compare both the files and get the differences in the third file along with the file name. Can anyone help me out with a simple command.

  • 5
    have you try man diff ? – Archemar Aug 10 '15 at 8:01

You can use grep function to see the difference (file3 is the output file):

grep -Fxvf file1 file2 > file3

Where the flags are:

  • -F : Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
  • -x : Select only those matches that exactly match the whole line.
  • -v : Invert the sense of matching, to select non-matching lines.
  • -f FILE : Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing.

Use flag -n : Prefix each line of output with the line number within its input file:

grep -n -Fxvf file1 file2 > file3

diff a b > differences should do the job. The differences between the two files will be stored in the file differences.

  • I have ">" in both of my files so how to take that into account? – Saket Agarwal Aug 10 '15 at 8:05
  • 1
    @SaketAgarwal diff "a>weird>filename" "b>also>weird>filename" > differences – scai Aug 10 '15 at 8:13

gnu diff

provided you have gnu diff (from diffutils, diff (GNU diffutils) 3.3).

diff --old-line-format='old %L' --new-line-format='new %L' --unchanged-group-format='' u v

old    PV Name                     /dev/dsk/c0t4d0
new    PV Name                     /dev/dsk/c99t4d0

(redirecting to a file is explain below).

basic diff with awk

with basic diff, use awk to parse '<' and '>'

diff u v
<    PV Name                     /dev/dsk/c0t4d0
>    PV Name                     /dev/dsk/c99t4d0

use awk to put file name

 diff u v | awk '$1 == "<" { printf "u: %s\n",$0; next ; } 
            $1 == ">" { printf "v: %s\n",$0 ; next ; } 
            { print;} '

u: <    PV Name                     /dev/dsk/c0t4d0
v: >    PV Name                     /dev/dsk/c99t4d0

(awk lines splitted for readability)

now to store into a diff file

diff u v | awk '$1 == "<" { printf "u: %s\n",$0; next ; } $1 == ">" { printf "v: %s\n",$0 ; next ; } { print;} ' > differences

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.