Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

bash - Print the output if the first column of three file match

I'm having 3 files with data as below:

File1-

a 10
b 20
c 30

File2-

a 11
b 22
c 45
d 33

File3-

a 23
b 33
c 46

I need to print the output like below if the first column of the three files matches:

a 10 11 23
b 20 22 33
c 30 45 46

I tried the below code but not getting the required output:

#!/bin/bash
awk 'FNR==NR{a[$1]=$2;next} {print $0,$1 in a?a[$1]:""}' File1 File2 File3
question from:https://stackoverflow.com/questions/65901773/print-the-output-if-the-first-column-of-three-file-match

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With your shown samples, could you please try following. Written and tested with GNU awk.

awk '
{
  arr[$1]=(arr[$1]?arr[$1] OFS:"")$2
  count[$1]++
}
END{
  for(key in arr){
    if(count[key]==(ARGC-1)){
      print key,arr[key]
    }
  }
}
'  Input_file1  Input_file2  Input_file3

NOTE: Just want to add here this answer to a new answer from all mentioned answers in shared dupe link under comments of question.

With shown samples output will be as follows.

a 10 11 23
b 20 22 33
c 30 45 46

Explanation: Adding detailed explanation for above.

awk '                                 ##Starting awk program from here.
{
  arr[$1]=(arr[$1]?arr[$1] OFS:"")$2  ##Creating arr with index of first field and value is 2nd field and keep appending its value in array.
  count[$1]++                         ##Creating count array with index of 1st field and keep increasing it.
}
END{                                  ##Starting END block of this program from here.
  for(key in arr){                    ##Traversing through all items in arr.
    if(count[key]==(ARGC-1)){         ##Checking condition if count with index of key is equal to ARGC-1 then print current item with its value.
      print key,arr[key]
    }
  }
}
' file1 file2 file3                   ##Mentioning Input_file names here.  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...