Kavitha
Kavitha

Reputation: 151

compare column one between two files and append the data from one file to another

I am having two files fileone and filetwo as below:

fileone:
    a   0   0
    b   4   3
    c   3   2
    f   3   2
filetwo:
    a   3
    b   2
    f   2

If column1 from fileone and column1 from filetwo are matcing then I need to append the column2 from filetwo to fileone as below:

Output:

    a   0   0   3
    b   4   3   2
    c   3   2
    f   3   2   2

I tried this but not getting the desired output:

#!/bin/bash
echo "These reports are based on this run:" ; pwd
echo " " ;
awk -F, 'FNR==NR {a[$1]; next}; $1 in a' fileone filetwo

Upvotes: 2

Views: 88

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133428

You were close, Input_file sequence you passed should be changed :) along with NOT having field separator as , in your attempt.

Could you please try following, written and tested with shown samples.

awk 'FNR==NR{a[$1]=$2;next} {print $0,($1 in a?a[$1]:"")}' Input_file2  Input_file1

Explanation: Adding detailed explanation for above.

awk '                              ##Starting awk program from here.
FNR==NR{                           ##Checking condition which will be TRUE when Input_file2 is being read.
  a[$1]=$2                         ##Creating array a with index of $1 and value of $2 here.
  next                             ##next will skip all further statements from here.
}
{
  print $0,($1 in a?a[$1]:"")      ##Printing current line and checking if 1st field is there in a then print a[$1] or print NULL.
}
' Input_file2  Input_file1         ##Mentioning Input_file names here.

OR in case you want to get good looking alignment try column:

awk 'FNR==NR{a[$1]=$2;next} {print $0,($1 in a?a[$1]:"")}' file2  file1 | 
column -t

Upvotes: 3

Related Questions