1

I'm trying to join two simple files in Solaris 5.8 Version as below:

~/temp/s: cat 1
work1 a 8058 51
work2 b 15336 51

~/temp/s: cat 2
8058 77-11:29:32 /apps/sas
15336 100-12:23:49 /local/hotfix

~/temp/s: join -1 3 -2 1 1 2
8058 work1 a 51 77-11:29:32 /apps/sas (The other line is missing from the output)

The output only contains one record where it should be two. I'm really not sure where it went wrong.

Is there any way we may get all the records in the output?

1

I think this might be a bug with join. I just tried it on Fedora 14 using this version of join:

$ join --version
join (GNU coreutils) 8.5

Example

$ join -1 3 -2 1 1 2
8058 work1 a 51 77-11:29:32 /apps/sas
15336 work2 b 51 100-12:23:49 /local/hotfix

Alternative

You could use awk to do this:

$ awk 'NR==FNR{_[$3]=$3;next}$1 in _{print _[$1],$0}' 1 2
8058 8058 77-11:29:32 /apps/sas
15336 15336 100-12:23:49 /local/hotfix
  • Also works for 5.97 – Bernhard Jul 31 '13 at 13:35
2

The join key must be sorted lexically.

So use a shell with support for process substitution (ksh93, zsh, bash) and:

join -1 3 -2 1 <(sort -k 3,3 1) <(sort -k 1,1 2)

Or with a POSIX/Bourne shell:

sort -k 3,3 1 | {
  sort -k 1,1 2 | join -1 3 -2 1 /dev/fd/3 -; } 3<&0

It helps to understand how join works. join reads the files concurrently line by line and compare the join keys, if they are the same we've got a match and output the result, if key1 < key2, keep reading file1 until key1 is equal to key2 (or greater, in which case we start reading file2 and so on).

That explains why it won't work if the files are not sorted by key.

Note that that's the case of every join but as an extension, GNU join doesn't complain as long as the keys match. It would fail like every other though, on the first mismatch if the lines are not sorted by key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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