Skip to main content
2 of 3
added 451 characters in body
Kusalananda
  • 356.6k
  • 42
  • 739
  • 1.1k

Using Miller (mlr) to read the data as "xtab" input (a format where records are separated by empty lines and fields are separated by newlines, with the field name and a tab at the start of the line), with the tabs in the format replaced by : (colon+space):

$ mlr --xtab --ips ': ' put -q 'print $dn, NF - 1' file [email protected],ou=test,dc=acme,dc=com 1 [email protected],ou=test,dc=acme,dc=com 2 [email protected],ou=test,dc=acme,dc=com 0 [email protected],ou=test,dc=acme,dc=com 1 

This simply outputs the dn field and the count of however many other fields there are in the record.

If you need commas in the output, use print $dn . ", " . string(NF - 1) as the put expression.

Alternatively, add the count as a new field and then cut out the dn field and your new field (output is on a whitespace-delimited indexed fields format ("nidx")):

$ mlr --x2n --ips ': ' put '$c = NF - 1' then cut -f dn,c file [email protected],ou=test,dc=acme,dc=com 1 [email protected],ou=test,dc=acme,dc=com 2 [email protected],ou=test,dc=acme,dc=com 0 [email protected],ou=test,dc=acme,dc=com 1 

Add --ofs ', ' to the options if you want comma+space as the output field delimiter.

Kusalananda
  • 356.6k
  • 42
  • 739
  • 1.1k