acidboy
acidboy

Reputation: 105

Personalize Diff Command in Ubuntu

I have two files, both with a lot of data, what I need is compare the first word of each file (each file always starts with a number, and each number could have many digits).

The files are identical when these numbers are the same.

Example: I have 3 files: a.txt, b.txt and c.txt

 a.txt content is "1 a b c 3 5 6 hjkj"
 b.txt content is "1 c f a 1234 h"
 c.txt content is "2 a b c 3 5 6 hjkj"

 diff a.txt b.txt should return "files are identical"
 diff a.txt c.txt should return "files are different"

How can I compare them using the diff command?

Upvotes: 0

Views: 117

Answers (3)

technosaurus
technosaurus

Reputation: 7802

It looks like you just want to check if the 1st "word" of the files match. This shell function should do that.

check_first_word(){
  read FIRST GARBAGE < $1
  read SECOND GARBAGE < $2
  [ "$FIRST" == "$SECOND" ] && echo "files are identical" || echo "files are different"
}

usage:

check_first_word file1 file2

Upvotes: 1

Giuseppe Pes
Giuseppe Pes

Reputation: 7912

This should do the job, put this function in your bashrc file.

function mydiff() {
       DIGITS=10
       file_1=`head -c ${DIGITS} $1`
       file_2=`head -c ${DIGITS} $2`

       if [ "$file_1" == "$file_2" ]
         then echo "Files are identical"
       else
         echo "Files are different" 
       fi
}

Usage :

mydiff file_1 file_2

Upvotes: 1

jkshah
jkshah

Reputation: 11703

Try using awk.

#!/bin/bash

awk 'FNR==1 { if(NR==1) a=$1; else b=$1 } END { if(a==b) print "files are identical"; else print "files are different" }' $1 $2

Store above command in file named mydiff, give executable permission using chmod +x and then you can execute personalized diff command as follows

mydiff file1 file2 

Upvotes: 1

Related Questions