LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   adding line from file1 into a line of another file based on maching IDs (https://www.linuxquestions.org/questions/programming-9/adding-line-from-file1-into-a-line-of-another-file-based-on-maching-ids-854028/)

rossk 01-03-2011 09:50 PM

adding line from file1 into a line of another file based on maching IDs
 
Hello

i wish to add information to one of my files based on matching IDs, here is an example

(the id is the 3 colunm)
File1.txt
v0001 bird 45
v0002 bird 47
v0003 cat 50
v0004 dog 56
v0005 dog 78

(the ID is the 2 colunm)
File2.txt
bird 45 age_7
cat 50 age_6
dog 56 age_5

and the output i wish to be

OUTPUT:
v0001 bird 45 age_7
v0002 bird 47
v0003 cat 50 age_6
v0004 dog 56 age_5
v0005 dog 78

so as you can see the ones that do not match are still present, and the ones that do match just have the extra information from file2.txt added to them.

i thought about using join but that only seems to join the ones that match displays thoes only. i would like all the information in the output file
please help! thank you all :)

rossk 01-03-2011 09:57 PM

PS. this is what command line i used

join -1 3 -2 2 file1.txt file2.txt

but as i said, it only displays the matching lines...

grail 01-03-2011 09:58 PM

Is it likely you can have the same ID but with a different animal? ie can you have dog 50 in either file?

rossk 01-03-2011 10:18 PM

Hi grail

Yes you can have a dog with a id of 50 and a cat with a ID of 50, but no 2 dogs will have the same ID. (in reality these files are organised so that all dogs are in a dog file and all cats are in a cat file etc.

example
dog.txt
v0004 dog 56
v0005 dog 78
v0006 dog 55

but the files are matched based on dog/cat/bird and there ID's (56, 78, 55 etc)

rossk 01-03-2011 10:24 PM

omg i forgot to mention i am programming in bash!

grail 01-04-2011 01:48 AM

Well awk seems to be well suited to this issue, something like:
Code:

awk 'FNR==NR{_[$1$2]=$3;next}$2$3 in _{$0=$0" "_[$2$3]}1' File2.txt File1.txt

rossk 01-06-2011 12:06 AM

Thanks heaps man!


All times are GMT -5. The time now is 09:03 PM.