6

I have this file1.txt

deiauk 9
kespaul 8
luktol 7 
titkur 6

and other file2.txt

kespaul b
deiauk a 

And I want to merge both files in one by first value, so my result should be

deiauk 9 a
kespaul 8 b
luktol 7 
titkur 6
3
  • Looks like there's a typo in file2.txt -- it should be "kespaul" not "kepsaul". Copy-and-paste at your own risk!
    – bgvaughan
    Jun 2, 2015 at 10:01
  • Why is there 4 spaces before deiauk 9 a? Is it the expected output? Jun 2, 2015 at 13:34
  • No I edit my question Jun 2, 2015 at 14:03

4 Answers 4

4

You can use join command (will be good to have files sorted)

join file1.txt file2.txt -a 1
1
  • 1
    Although sort-ing is needed too..
    – heemayl
    Jun 2, 2015 at 10:00
3

With awk you can do:

awk '
  NR==FNR { k[$1]=$2; next }
  { print $0, k[$1] }
' file2.txt file1.txt

Note: This awk solution works also on unsorted raw input data; no need for additional expensive processes.

2
sort file2.txt | join -a 1 file1.txt -

join requires sorted input. The '-' specifies that standard input will be used for the second file, which allows the output of sort to be used as input. The '-a 1' specifies that non-matching lines from the first file will be included in the output.

1
  • 2
    Actually, I think heemayl's solution, in the comment to another answer, is better than mine, since it's a more generalized solution. Mine only works if file1.txt is already sorted. join -1 1 -2 1 -a 1 <(sort f1.txt) <(sort f2.txt)
    – bgvaughan
    Jun 2, 2015 at 10:29
1

Files must be sorted, so here's everything on one line.

sort file1.txt > f1s ; sort file2.txt >f2s ; join  -1 1 -2 1 -a 1 -a 2 f1s f2s ; rm f1s f2s
2
  • 6
    Use join -1 1 -2 1 -a 1 <(sort f1.txt) <(sort f2.txt)
    – heemayl
    Jun 2, 2015 at 10:07
  • 1
    Nice improvement !
    – X Tian
    Jun 2, 2015 at 10:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .