Concatainate two files base on ID [solved]

Hello my fellow linux people,

There are two files which are structured like this:

file1.txt
badgeID,empNum

file2.txt
empNum,usrName

Both have many entries - How can I concatenate these two files so it becomes one glorious file like so:

file3.txt
badID,empNum,usrName

In other words in a "primary/foreign" key based on empNum - how can i concatenate these two files??? Suggestions???

ANSWER FOR ANYONE WHO EVER NEEDS THIS THREAD AGAIN

join -t, -1 2 -2 1 -o 1.1 1.2 2.3 file1.txt file2.txt > file3.txt

Thanks @Eden

redirect output of both files into variables then concatenate the variables. Should be able to do it in bash.

I was considering join also.

assuming they are in order already

join -t, -1 2 -2 1 -o 1.1 1.2 2.3 file1.txt file2.txt > file3.txt

-t, sets the deliminator to ,
-1 2 and -2 1 says use column 2 from file 1 and column 1 from file 2 as the key
-o 1.1 1.2 2.3 sets the output order first column and seconf column from file 1 and third column from file 2

1 Like

touch combined.txt
cat file1.txt >> combined.txt
cat file2.txt >> combined.txt
cat file3.txt >> combined.txt
cat filen.txt >> combined.txt
">>" means attach to file aka. concatenate.
not sure if it is what you need, maybe just create a parser, which does the same.

Tried this got an error:

var1=""
var2=""

cat ./file1.txt > $var1
cat ./file2.txt > $var2

cat $var1 $var2 > ./combine.txt

I don't really need to append the files as much as attach matching columns based upon a field.

For example

file1.txt

001,bnye
002,pcollins
003,owinfrey

file2.txt
009,001
008,002
007,003

create file3.txt
001,bnye,009
002,pcollins,008
003,owinfrey,007

That did it.

Thanks!

...let's see if I can break it.