using field 2 in file2 to complete field 3 in file1

Hello,

I was hoping someone could help me with this work related problem...

basically what I want to do is the following:

file2:

1 o
2 t
4 f
5 v
7 n
8 e
10 a

file1:

1 :
2 :
3 :
4 :
5 :
6 :
7 :
8 :
9 :
10 :

Output:

1 : o
2 : t
3 :
4 : f
5 : v
6 :
7 : n
8 : e
9 :
10 : a

I am using "foreach" to implement this and it works fine when the number of lines is low, but when I hit numbers in the thousands the script becomes really slow.
I am sure there is a faster way of doing this using awk or sed but just dont know the command.
if you could also provide an explanation of the command that implements this I would appreciate it.

Thanks,

awk 'NR==FNR {_[$1]=$2; next} _[$1] {print $0 FS _[$1]; next}1 ' file2 file1
1 : o
2 : t
3 :
4 : f
5 : v
6 :
7 : n
8 : e
9 :
10 : a
1 Like

If the real files are sorted you should just be able to use join:

join -a1 file1 file2

(untested)

1 Like

Thanks guys, I will try both methods and let you know.

---------- Post updated at 04:44 AM ---------- Previous update was at 04:12 AM ----------

Hi zaxxon, this is what I got when I tried your method:

 
> awk 'NR==FNR {_[$1]=$2; next} _[$1] {print $0 FS _[$1]; next}1 ' Site_Package.txt user_input.txt
awk: syntax error near line 1
awk: bailing out near line 1
> echo $SHELL
/usr/bin/tcsh
> 

Hi CarloM,
Your method also didnt work for me:

 
> join -al user_input.txt Site_Package.txt 
usage: join [-a file_number | -v file_number] [-o list [-e string]]
[-t char] [-1 field] [-2 field] file1 file2
join [-a file_number] [-j field] [-j1 field] [-j2 field]
[-o list [-e string]] [-t char] file1 file2
 

any other way of doing it?

Works like a charm when using nawk, thanks alot guys :slight_smile:

That's a one, not the letter L.

oh sorry about that, my eyes are getting really tired, its really late here :(, will try tomorrow and let you

Hi CarloM,
My files are not sorted so "join" would not work properly
but I did not know about join, am sure i will use it later on.

Thanks