2

This question already has an answer here:

My files:

file1.txt
 =========
 key1
 key1
 key1
 key1   
 key2
 key2   
 key3
 key3
 key3
 key4
 key4   

 file2.txt
 =========
 key1   22
 key2   23
 key3   24


 Expected Output :
 ==================
 key1   22
 key1   22
 key1   22
 key1   22    
 key2   23
 key2   23   
 key3   24
 key3   24
 key3   24

All solutions that I found does not duplicate matches strings.

awk '{a[$1]=a[$1]" "$2} END{for(i in a)print i, a[i]}'
join -a 1

What needs to be modified in this approaches to result in a left outer join?

marked as duplicate by Community Mar 1 '18 at 21:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    join file1.txt file2.txt works for me. – Stéphane Chazelas Mar 1 '18 at 21:49
  • I have different encodings. Thank you for the answer! – Korolenko S Mar 1 '18 at 21:55
  • The files MUST BE SORTED before JOIN – Korolenko S Mar 1 '18 at 22:40
2

Awk solution:

awk 'NR==FNR{ a[$1]=$2; next }$1 in a{ $2=a[$1]; print }' file2.txt file1.txt

The output:

key1 22
key1 22
key1 22
key1 22
key2 23
key2 23
key3 24
key3 24
key3 24

Or simply with join command:

join -o1.1,2.2 file1.txt file2.txt

Not the answer you're looking for? Browse other questions tagged or ask your own question.