Skip to content
Advertisement

conditionally merge files by appending in bash

I have two files and would like to merge them – by appending to the last line.

file1.txt content

gitTrial 161 1.5 154.5 2 0 161 154.5 1.5
Yahoo 122 0.5 120.5 2 0 122 120.5 0.5
Stack 122 0.5 120.5 2 0 122 120.5 0.5

file2.txt content

 gitTrial 90
 Yahoo    91

Desired outcome – file3.txt

gitTrial 161 1.5 154.5 2 0 161 154.5 1.5 90
Yahoo 122 0.5 120.5 2 0 122 120.5 0.5 91
Stack 122 0.5 120.5 2 0 122 120.5 0.5 0

How do I go about this, please?

Note, zero is in place for null in the Stack line.

Advertisement

Answer

Using awk:

awk '
  NR==FNR{ a[$1]=$2; next }
  { print $0, ($1 in a ? a[$1] : 0) }
' file2.txt file1.txt > file3.txt

When file2.txt is read, store field2 in array a using field1 as index.
When file1.txt is read, print the line plus the value of array a at index of field1 if present or 0 otherwise.
Redirect output to file3.txt.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement