2

Is it possible to use a variable as the index to a true multidimensional array? I have an gawk 4.1.1 script that runs through Cisco configuration files, and I want to create an array that looks like:

myarray[sitecode][switchname]

Where sitecode and switchname are pulled from the FILENAME being processed, and then additional indexes beyond that to calculate various things on a per-switch basis. For those two indexes above, I want to set both the index and the value to the same variable. So eventually I could have an array that looks like:

myarray[nyc01][switch01][Vlan100][192.168.100.1]
myarray[nyc01][switch01][Vlan101][192.168.101.1]
myarray[nyc01][switch02][Vlan200][192.168.200.1]

The code below illustrates what I am trying to do:

#!/bin/bash
awk '{
var1="variable1"
var2="variable2"
array[var1]=var1
array[var1][var2]=var2
print array[var1][var2]
}'

I get this error:

awk: cmd. line:6: (FILENAME=- FNR=1) fatal: attempt to use scalar `array["variable1"]' as an array

I sort of understand why it's happening. I have declared var1 and var2 to be scalar variables. But is there a work around for what I am trying to do?

refriedjello
  • 657
  • 8
  • 18
  • array[var1]=var1: the left hand side of the assignment is a row of the array (or a plane if you have a 3D array), the rhs is single value. Are you trying to assign the entire n-1 dimension at once??? – user1666959 Jun 06 '14 at 20:03

1 Answers1

1

When you set array[var1] = var1, you are setting that element to hold a scalar.
Then you try to array[var1][var2] = var2, you want to redefine the kind of thing that get stored at array[var1]. Quoting from the manual

The type of any element that has already been assigned cannot be changed by assigning a value of a different type. You have to first delete the current element, which effectively makes gawk forget about the element at that index:

(emphasis mine)

I see that if you try your assignments in the other order, you get a different but corresponding error message

% awk 'BEGIN {v1="foo"; v2="bar";a[v1][v2] = v2; a[v1]=v1}'
awk: cmd. line:1: fatal: attempt to use array `a["foo"]' in a scalar context

You can just stick with simulated multidimensional arrays:

$ awk 'BEGIN {v1="foo"; v2="bar"; a[v1] = v1; a[v1,v2] = v2; print a[v1,v2]}'
bar
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • I was just realizing that now. I was thinking for some reason I could make array[var1] contain both a scalar value and another array - array[var1][var2]. Once I realized that and said it aloud to myself, I felt pretty silly. I actually read that bit from the manual, but the significance of it eluded me. Thank you for your response :) – refriedjello Jun 06 '14 at 20:34
  • 1
    I notice you've never accepted answers to any of your questions. To be a responsible member of the commumity, please read through http://stackoverflow.com/help/asking – glenn jackman Jun 06 '14 at 21:42