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!

Pass an array variable to AWK

Status
Not open for further replies.

mittko

Programmer
Oct 6, 2008
1
US
I have a question about passing an array variable to AWK - is this possible?
For example, I have an array defined in C shell:

Code:
set array = ( 3 43 56 39 40 100 2 33 )

I want to invoke an AWK script that can use this array:

Code:
awk -f script.awk -v SomeVar1=5 -v ArrayVar=$array < input.dat > output.dat

However, this does not work. Is there a way to do that?
To save some questions, I am trying to do the following:

==========
Have a file1:

Code:
file1.dat (300 lines)
--------
1   3
2   43
3   56
4   39
...
300 18
--------

Basically, my array variable above is made of the second column of this file. Without using the "-v ArrayVar=$array" option in the awk command line above, I obtain the following output file (simplified version):

Code:
output.dat (562 lines)
---------
1  abb
2  abb
2  abb
3  abc
3  abc
4  abb
5  abc
5  abc
6  abb
7  abb
7  abb
...
300 abb
---------

So, I want to add the second column of "file1.dat" as a third column in my "output.dat" so that the correspondence between the first and second column in "file1.dat" is kept, i.e. I want to get:

Code:
outputWanttoObtain.dat (562 lines)
---------
1  abb  3
2  abb  43
2  abb  43
3  abc  56
3  abc  56
4  abb  39
5  abc  40
5  abc  40
6  abb  ...
7  abb
7  abb
...
300 abb ... 
---------

If I can pass an array from C shell to awk, this can be easily done. If not, I cannot come up with a few lines easy solution, so any advice would be appreciated.
=============
 
Populates your array in awk:
awk '
NR==FNR{ArrayVar[$1]=$2;next}
yourProgram here
' file1.dat input.dat >output.dat

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top