Skip to main content
4 of 4
added 74 characters in body
jimmij
  • 48.7k
  • 20
  • 136
  • 141

With awk:

awk -F: 'NR==FNR{a[$1]=$2;next}a[$2]{print $1":"$2":"a[$2]}' file1 file2

Output:

bart:29482164591748:computer
smithers:68468468468464:keyboard
lisa:68468468468464:keyboard

Explanation:

  • awk -F: start awk treating colon as a fields delimiter
  • NR==FNR{} process only the first file
  • a[$1]=$2;next build an array a indexed by the first field with values of the second field then skip to the next row
  • a[$2]{} process only if value of previously build array with the index of the current second field is not empty (this is done only for the file2, because of the next word in the previous expression)
  • print $1":"$2":"a[$2] print everything as desired

After question edit:

awk -F: 'NR==FNR{a[$1]=$2;next}a[$2]{print $1":"$2":"a[$2]}' file2 file1

Output:

bart:29482164591748:computer
 apu:29482164591748:computer
smithers:68468468468464:keyboard
lisa:68468468468464:keyboard
jimmij
  • 48.7k
  • 20
  • 136
  • 141