4

This question already has an answer here:

I have two files with one column.
If the first rows in the two files are same, then print 1 otherwise print 0.

file1:

M
A
A
M

file2:

M
M
A
A

output:

1
0
1
0

Can anybody show me an awk script which would do this?

marked as duplicate by Kusalananda awk Apr 21 at 7:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • What is field separater of two files? – cuonglm May 26 '14 at 7:12
5

Try this:

$ awk '!NF{next} FNR==NR{a[FNR]=$1;next};{print $1==a[FNR]  ? 1 : 0}' file1 file2
1
0
1
0

Explanation

  • !NF{next}: we don't need blank lines, skip it.
  • FNR==NR{a[FNR]=$1;next}: while processing file1, we save its first field to associative array, with index is the line number.
  • {print $1==a[FNR] ? 1 : 0}: while processing file2, we check if the first field value equals with corresponding file1 value, which saved in associative array a. If yes print 1 else print 0.
4
paste file1 file2 | while read a b; do [[ $a != "$b" ]]; echo $?; done

the [[ command returns a 0 status upon success and 1 on failure.

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