Template to extract battery levels off spesific named sensors

Hi, I have a working-ish template for counting batteries with a level >90% for example.
{{ states.sensor | selectattr('attributes.device_class', 'eq', 'battery') | selectattr('state', '>=', '90') | list | length }}

BUT how could I edit this template to only include sensors that has for example “pir” in their entity_id?
Additionally, how can I possibly average the result from that to show a “average” battery level?

I find myself adding devices and updating the sensors to include new devices is not very efficient, so I want to have a function that automatically checks all battery levels (and z-wave devices online/offline etc)

In the end I want to have a notification sent to me with a list of devices that are running low on batteries and possibly the type of battery they need replaced :slight_smile: