3

I have two files. I want to compare the content of one file with the other one. If there is a matching line between both files then print the line and its line number in each file. Example:

File 1:

ABC
PQR
MNO
XYZ

File 2:

qqqq
wewe
ABC
acdd
abcc
nop
MNO

Expected output:

ABC       1      3
MNO       3      7
..
2

With awk you could process the first file, store the lines ($0) and their corresponding line numbers (NR) (as indices/values) in an associative array (l[$0]) then process the second file and if a line is in the the array index print it along with the value of l[$0] and current line number (FNR):

awk 'FNR==NR{l[$0]=NR; next}; $0 in l{print $0, l[$0], FNR}' file1 file2
1
#!/bin/sh

count_match() {
    grep -x -n -F -f "$1" "$2" | sed 's/\([0-9]*\):\(.*\)/\2 \1/' | sort
}

count_match file2 file1 > /tmp/$$A
count_match file1 file2 > /tmp/$$B
join /tmp/$$[AB]

rm /tmp/$$[AB]

These are the grep options used:

-n print matching line numbers
-x match whole lines only
-F match literal strings -- no regular expressions
-f filename read the search patterns from a file (in our case either file1 or file2)

Use sed to switch the order of the fields and drop the colon :.

sort the output.

join the contents of the two temporary files.

This demonstrates the usage and output of commands in the above example:

$ grep -n -F -f file2 file1
1:ABC
3:MNO
$
$ grep -x -n -F -f file2 file1 | sed 's/\([0-9]*\):\(.*\)/\2 \1/' 
ABC 1
MNO 3
$
$ grep -x -n -F -f file1 file2 | sed 's/\([0-9]*\):\(.*\)/\2 \1/'
ABC 3
MNO 7
$ 

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.