1

I'm pretty new to awk/gawk and I found this a little confusing. I hope you may help me shed some light on this question: Are strings in awk treated as array of chars?

I've read something about the stringy-ness of this computing language, so I tried to make a script like this:

BEGIN {
   myArray[1] = "foo"
   myArray[2] = "bar"
   myArray[3] = 42

   awkward()
}

function awkward() {
    for (j in myArray) {
        for (d in myArray[j]) {
            # error!
        }
    }
}

Was I naive in thinking something like this could work? It actually does not work with my version of gawk, giving me this error:

for (d in myArray[j]) {
                 ^ syntax error

Can anybody help me to understand more about why this should not work? Bonus: can anybody share their workaround on this?


To clarify a bit, I'm trying to access the content of myArray[j] char by char, using a for loop on index d.

Daemon Painter
  • 3,208
  • 3
  • 29
  • 44
  • Thanks, that is a nice workaround @MichaWiedenmann. It is indeed a way to achieve the goal, yet does not explain why this does not turn magically into a multidimensional array. – Daemon Painter Feb 14 '18 at 14:41
  • @DaemonPainter see also https://www.gnu.org/software/gawk/manual/html_node/Arrays-of-Arrays.html and https://www.gnu.org/software/gawk/manual/html_node/Multidimensional.html – Sundeep Feb 14 '18 at 15:12

1 Answers1

2

No, strings in awk are not treated as array of chars. Use substr():

$ cat foo.awk
BEGIN {
   myArray[1] = "foo"
   myArray[2] = "bar"
   myArray[3] = 42

   awkward()
}

function awkward() {
    for (j in myArray) {
        for (i=1;i<=length(myArray[j]);i++) {  # here
            print substr(myArray[j],i,1)       # and here
        }
    }
}

Run it:

$ awk -f foo.awk
f
o
o
b
a
r
4
2
James Brown
  • 36,089
  • 7
  • 43
  • 59