user2328149
user2328149

Reputation: 737

How to merge text files with common pair of strings in their lines

I have two text files with the following line format:

Value - Value - Number

I need to merge these files in a new one that contains only the lines with the common Value - Value pairs followed by the two Number values.

For example if I have these files:

File1.txt

Jack - Mark - 12
Alex - Ryan - 15
Jack - Ryan - 22

File2.txt

Paul - Bill - 11
Jack - Mark - 18
Jack - Ryan - 20

The merged file will contain:

Jack - Mark - 12 - 18
Jack - Ryan - 22 - 20

How can I do this?

Upvotes: 1

Views: 60

Answers (1)

karakfa
karakfa

Reputation: 67507

awk to the rescue!

awk -F' - ' 'BEGIN{OFS=FS} 
           NR==FNR{a[$1,$2]=$3;next} 
      ($1,$2) in a{print $1,$2,a[$1,$2],$3}' file1 file2

Jack - Mark - 12 - 18
Jack - Ryan - 22 - 20

alternatively, with decorate/join/undecorate

$ join <(sort file1 | sed 's/ - /-/') <(sort file2 | sed 's/ - /-/') |
  sed 's/-/ - /'

Jack - Mark - 12 - 18
Jack - Ryan - 22 - 20

Upvotes: 2

Related Questions