1

I am using a 2D array to save the number of recurrences of certain patterns. For instance:

$4 == "Water" {s[$5]["w"]++}
$4 == "Fire" {s[$5]["f"]++}
$4 == "Air" {s[$5]["a"]++}

where $5 can be attack1, attack2 or attack3. In the END{ }, I print out these values. However, some of these patterns don't exist. So for s["attack1"]["Air"] =0, my code prints whitespace. Hence I would like to know if there is a way to initialize the array in one line instead of initializing each of the elements I need, in the BEGIN{ }.

  awk -f script.awk data

This is the command I am using to run my script. I am not allowed to use any other flags.
EDIT 1:
Here's the current output

              Water        Air        Fire
attack1       554                     12
attack2       14           24              
attack3       6                       3

Here's the output I desire:

              Water        Air        Fire
attack1       554          0          12
attack2       14           24         0    
attack3       6            0          3
4
  • It's very unclear what it is you want or why printing whitespace is bad thing or why you don't just print the populated values if you're unhappy getting whitespace for unpopulated values. Edit your question to contain a concise, testable example including sample input and expected output and an explanation. Also - are you using a version of GNU awk that supports true multi-dimensional arrays or not? Commented Feb 15, 2016 at 2:56
  • @EdMorton, I added the current output I have. And I believe the GNU supports the true multi-dimensional arrays, because it is working the way it should be. Commented Feb 15, 2016 at 3:42
  • It might be much easier if you switched to a 2D array (i.e. a[i,j]) rather than an array of arrays (i.e. a[i][j]). Note also that in awk, a[i]++ is legal (so long as i has been defined), even if a[i] has not been initialized, so explicit initialization is often unnecessary. Commented Feb 15, 2016 at 3:45
  • OK, you added the output. Good. Now add the input that would produce that output and you will have the start of a question that we can help you with. Commented Feb 15, 2016 at 13:28

1 Answer 1

2

You don't need to initialise the array in this case. Awk already has a default empty value, so you just have to change the way you print the value.

Observe:

awk 'BEGIN {print "Blank:", a[1];
            print "Zero: ", a[1] + 0;
            printf("Blank: %s\n", a[1]);
            printf("Zero: %i\n", a[1])}'

Output:

Blank:
Zero:  0
Blank:
Zero: 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.