0

I want to run a for loop in awk with leading zeros in the index variable.

This isn't for printing a number with leading zeros, which I could easily handle with a printf statement. It's for checking if the given number (with leading zeros) has been used as an index in an array.

So what I actually want is to iterate through string values in awk, from "01" to "14" (or whatever).

Something like:

myarray["01"]
myarray["02"]
myarray["04"]
myarray["05"]
# ... etc, up to "12"

for (i = 01; i <= 12; i++) {
  if (! (i in myarray)) {
    print i " is missing from myarray"
  }
}

Should report that "03 is missing from myarray." But that's not how it works.

How can I do this?

0

1 Answer 1

4

Just use sprintf:

BEGIN {
  myarray["01"]
  myarray["02"]
  myarray["04"]
  myarray["05"]
  # ... etc, up to "12"

  for (i = 1; i <= 12; i++) {
    k = sprintf("%02d", i)
    if (! (k in myarray)) {
      print k " is missing from myarray"
    }
  }
}

gave you:

03 is missing from myarray
06 is missing from myarray
07 is missing from myarray
08 is missing from myarray
09 is missing from myarray
10 is missing from myarray
11 is missing from myarray
12 is missing from myarray

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.