uitty400
uitty400

Reputation: 277

Access a bash array in awk loop

I have a bash array like

myarray = (1 2 3 4 5 ... n)

Also I am reading a file with an input of only one line for example:

1 2 3 4 5 ... n

I am reading it line by line into an array and printing it with:

awk 'BEGIN{FS=OFS="\t"}
     NR>=1{for (i=1;i<=NF;i++) a[i]+=$i}
     END{for (i=1;i<NF;i++) print OFS a[i]}' myfile.txt

myarray has the same size as a. Now myarray starts with the index 0 and a with index 1. My main problem though is how I can pass the bash array to my awk expression so that I can use it inside the print loop with the corresponding elements. So what I tried was this:

awk -v array="${myarray[*]}"
    'BEGIN{FS=OFS="\t"}
     NR>=1{for (i=1;i<=NF;i++) a[i]+=$i}
     END{for (i=1;i<NF;i++) print OFS a[i] OFS array[i-1]}' myfile.txt

This doens't work though. I don't get any output for myarray. My desired output in this example would be:

1   1
2   2
3   3
4   4
5   5
...
n   n

Upvotes: 1

Views: 797

Answers (1)

fedorqui
fedorqui

Reputation: 289745

To my understanding, you just need to feed awk with the bash array in a correct way. That is, by using split():

awk -v bash_array="${myarray[*]}" 
     'BEGIN{split(bash_array,array); FS=OFS="\t"}
      NR>=1{for (i=1;i<=NF;i++) a[i]+=$i} 
      END{for (i=1;i<NF;i++) print a[i], array[i]}' file

Since the array array[] is now in awk, you don't have to care about the indices, so you can call them normally, without worrying about the ones in bash starting from 0.

Note also that print a,b is the same (and cleaner) as print a OFS b, since you already defined OFS in the BEGIN block.

Upvotes: 2

Related Questions