Script group all switches with specific prefix

Is there a way to script a group with all switches whose names begin with a certain prefix.

I already have something like this

    - service: group.set
        object_id: "all_automations"
        entities: "{{ states.automation | map(attribute='entity_id') | join(',') }}"

but now I need a group of every switch starting with switch.nr_automation_

Is this doable?

Have a look at the templates here:

Thanks Tom! My other group scripts are based on this. The only thing I don’t know how to do ist the “starts with …” part.

I know that I can do stuff like this

{% set domain = 'switch' %}
{% set prefix = 'nr_automation_.*' %}
{{ states[domain] | map(attribute='entity_id') | map('regex_search', prefix) | list | join(', ') }} 

but this only gives me False, False, False, False, False, True, True, True, True, False, False and not the entities

Try this in the template editor:

{{ states['switch'] | map(attribute='entity_id') | selectattr('entity_id','contains', 'nr_automation_') | list | join(', ') }}
1 Like


There’s no Jinja2 test called contains.

Jinja2 Built-in Tests

Try this:

{{ states.switch
   | map(attribute='entity_id')
   | select('>', 'switch.nr_automation_')
   | select('<', 'switch.nr_automation_x')
   | join(',') }}

Example from my test system using input_booleans:

1 Like

Damn. That would be too easy.

This does indeed work! Thanks!

1 Like

Glad to hear that it answered your question. Please consider marking my post (above) with the Solution tag. It will automatically place a check-mark next to the topic’s title which indicates to other users that this topic has an accepted Solution. It will also automatically place a link beneath your first post that leads to the Solution topic. All of this helps other users find answers to similar questions.

Over a year has passed since the last post was written and there are now new ways of achieving the result that are more efficient (using either match or search).

{{ states.switch | map(attribute='entity_id') | select('match', 'switch.schedule_') | join(',')  }}

The point of my post was that you exhumed a thread that’s been dead for over a year to recommend users employ an outdated technique:

For anyone else looking to enable and disable schedules in bulk:

To learn about Jinja2 templating in Home Assistant, its best to start with the official documentation’s section on Templating. That section contains links to other important references including the official documentation for the Jinja2 templating language. The important thing to keep in mind is that Home Assistant doesn’t support everything described in Jinja2’s documentation and Home Assistant has its own extensions to Jinja2.

My apologies for polluting your dead thread. I’ll delete my posts.