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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

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

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
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

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.