Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

file1:

M
A
A
M

file2:

M
M
A
A

output:

1
0
1
0

Can anybody tell me the awk script?

share|improve this question
    
What is field separater of two files? –  cuonglm May 26 at 7:12

2 Answers 2

paste file1 file2 | while read a b; do [[ $a != "$b" ]]; echo $?; done

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

share|improve this answer

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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