Command_line sensor and the (double) quote issue

Easy question: how to use this command

cat /config/.storage/core.device_registry | grep -c '"config_entries": '

(which is working perfectly on the command line) into a proper command for a command_line sensor?

I tried every possible constellation but HA refuses to create the sensor (config check fails). I’m pretty sure I ran into the famous quote/double quote issue with command_line sensors. What’s the allround solution to that problem?

The latest definition

command: 'cat /config/.storage/core.device_registry | grep -c '"config_entries": ''

gives

Error loading /config/configuration.yaml: while parsing a block mapping
  in "/config/integrations/system_statistics.yaml", line 803, column 5
expected <block end>, but found '<scalar>'
  in "/config/integrations/system_statistics.yaml", line 809, column 68

(where 68 is the first appearing ")

:x: escaping the "s does not work
:x:using double quotes instead of single ones on the outside did not work

Freaking me out.

How were you escaping the quotes?

In yaml a single quote is escaped with another single quote, not a backslash.

command: 'cat /config/.storage/core.device_registry | grep -c ''"config_entries": '''

The other option is to use a multi-line template that does not require quoting:

command: > 
  cat /config/.storage/core.device_registry | grep -c '"config_entries": '
2 Likes

In addition to what tom_l wrote, cating files to grep is just unnecessary overhead. grep can read files directly:

command: >
  grep -c '"config_entries": ' /config/.storage/core.device_registry
2 Likes

Nice. Thanks for that improvement. Does this work for advanced commands too where multiple pipes are used? In other words: dropping the cat is the only iteration I can achieve? Like

cat /config/.storage/core.device_registry | grep 'deleted_devices' -B 100000 | grep -c '"config_entries": '

I can (only) make this out of it:

grep 'deleted_devices' -B 10000 /config/.storage/core.device_registry | grep -c '"config_entries": '

I don’t think so, at least not with grep. I guess you could do it with awk or sed, but I don’t think it’s worth it.