Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conditional merge two files with awk 1

Status
Not open for further replies.

FedoEx

Technical User
Oct 7, 2008
49
US
Hello.
I am in a process of learning awk.
I read and tested most of the examples in the gnu awk users guide regarding the arrays.
I also went through this forum in search for solution to my current problem.
I have one file with about thousand lines which looks like that.

data1
S 1 A 20 12.33
S 2 A 22 11.11
S 3 A 23 12.56
S 4 A 100 23.34
S 5 A 14 11.23
S 6 A 23 34.12

And I have a second file

data2
2 3.344475e-02 3.42
3 3.997639e-02 3.32
5 3.549071e-03 3.93

The desired output is

2 3.344475e-02 S 2 A 22
3 3.997639e-02 S 3 A 23
5 3.549071e-03 S 5 A 14

I am trying to read the data2 file first and then paste the lines with the matching fields between
Code:
awk -F , 'BEGIN {
    while ((getline < "data2") > 0)
        datarr[$1] = $2
    }
{if (datarr[$2])
        print datarr[$1] ,$1,$2,$3
}' data1

I need something in the context of the above script. I think the problem is that I need to read the files as multidimensional arrays.
Can someone help me please. The solution must be with awk since this is a piece of a bigger script.
 
Hi

Why you specify the comma ( , ) as fields separator ? Remove that.
Code:
awk 'BEGIN {
    while ((getline < "data2") > 0)
        datarr[$1] = $2
    }
{if (datarr[$2])
        print $1,datarr[$2] ,$1,$2,$3
}' data1

Feherke.
 
Thanks.
The original data file had a lots of special characters like (, . {}) so I used
Code:
awk  '{gsub(/}|{|,|"/," ");printf( .......... )}'  data.orig
to get rid of it.
So I must have forgotten the comma when I was trying different things with chunks from the original data file.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top