count number of values in each field in awk, output table
<p>I'm trying to count the number of elements/words present in each field of a big table. Fields are delimited by whitspaces, and field elements ("words") by commas. The table also contains empty fields (e.g. two or more consecutive whitespaces), which is equivalent to 0 elements.</p>

<p>For example, from a table such as this:</p>

<pre><code>val1 this,is,text this,more,text  stop
val2  this,is a field
val3    end,text
</code></pre>

<p>This would be the desired output:</p>

<pre><code>val1 3 3 0 1
val2 0 2 1 1
val3 0 0 0 2
</code></pre>

<p>(I'd like to keep the first column as is)</p>

<p>Please note that there are two blank spaces before the <code>stop</code> value in the first line, indicating that the fourth field has 0 elements. Similar things happen in other lines.</p>

<p>I've been using the split function of awk to create an array with the desired number of elements for each field:</p>

<pre><code>awk '{ for(i = 2; i &lt;= NF; i++) {
$i=split($i,a,",") ; { if (!$i) { $i="0" }};
}; print $0}' input
</code></pre>

<p>I'm splitting each field <code>i</code> into an array <code>a</code> of <code>n</code> elements, and assigning this value to the variable <code>$i</code>. In the case of 0 elements in the given field, (<code>!$i</code>), <code>$i=0</code>.</p>

<p>But this is my current, unwanted output:</p>

<pre><code>val1 3 3 1
val2 2 1 1
val3 2
</code></pre>

<p>As you can see, 0 values are omitted. I think that there's some issue with the assignment of the 0 value to empty fields. </p>

<p>Can anyone help me? Thanks a lot in advance!</p>