Question

Input:

File 1
col1 col2 col3 col4 col5 col6 col7
A     91    -    E    Abu    7    -
B     82    -    f    Anu    9    -       
C     93    -    G    Aru    8    -

File 2
col1 col2 col3 col4 col5 col6 col7
A     91    -    x    Bob    7    -
B     82    -    y    Bag    9    -       
C     93    -    z    Bui    8    -

File 3
col1 col2 col3 col4 col5 col6 col7
A     91    -    T    Can    7    -
B     82    -    U    Con    9    -       
C     93    -    V    Cuu    8    -     

Output Expected:

col1 col2 col3 col4 col5
A     91  Abu  Bob  Can    
B     82  Anu  Bag  Cun           
C     93  Aru  Bui  Cuu

I have three files having same data at col1 and 2. I need to print fifth column of all files along with first two column. I am able to do using two files. So Can anyone help me to do with three and more files?

Was it helpful?

Solution

Here is one way using awk:

$ awk '
BEGIN {
    SUBSEP = FS;
    print "col1 col2 col3 col4 col5"
}
FNR>1 {
    a[$1,$2] = (a[$1,$2]?a[$1,$2]FS$5:$5)
}
END {
    for(x in a) print x, a[x]
}' file1 file2 file3
col1 col2 col3 col4 col5
C 93 Aru Bui Cuu
A 91 Abu Bob Can
B 82 Anu Bag Con

You can pipe the output to sort if you required sorted output. This does not limit to three files. It is scalable to n number of files. Just add the file names at the end or use * to glob to all files under a given directory.

OTHER TIPS

Assuming all three files have same number of rows because of this sentence

I have three files having same data at col1 and 2.

awk 'BEGIN{OFS="\t";
getline<"file1";getline<"file2";getline<"file3";
print "col1","col2","col3","col4","col5";
while(1) {getline < "file1";a=$1;b=$2;c=$5;getline<"file2";d=$5;f=getline<"file3";e=$5;
if(!f)exit;print a,b,c,d,e}}'  

Output:

col1    col2    col3    col4    col5
A       91      Abu     Bob     Can
B       82      Anu     Bag     Con
C       93      Aru     Bui     Cuu

This will discard first line of each file, then reads files line by line, printing desired fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top