A little script to clean up MQTT retained topics

This might be unique to my setup and my inexperience with Zigbee2MQTT, Home Assistant, RTL_433, OpenMQTT Gateway etc. But I ended up with many, many unwanted devices being auto discovered. This is the way I cleaned up the retained topics in my broker:

How many Auto Discovered OpenMQTTGaetwayretained topics do I have?
mosquitto_sub -t “#” -v --retained-only -h gx100.local | awk ‘{gsub(/[^\x00-\x7F]/, “”)} 1’ | grep -a stat_t | wc -l

NB: “stat_t” was unique to the ones I wanted to remove.

List those unwanted topics, put them in a file along with a mosquitto_pub command to delete them:
mosquitto_sub -t “#” -v --retained-only -h gx100.local | awk ‘{gsub(/[^\x00-\x7F]/, “”)} 1’ | grep -a stat_t | sed ‘s/config.*/config/’ | sed ‘s/^/mosquitto_pub -h broker.local -n -r -d -t "/’ | sed ‘s/$/"/’ > cleanup_topics.sh

NB: replace broker.local with your MQTT broker’s address
I’m no sed/awk wizard, I think these commands could be made better.

First awk attempts to strip out non-ASCII data from stream.
Then grep for “stat_t” which was unique to topics from OpenMQTTGateway.
Then strip everything after “config”.
Then insert ‘mosquitto_pub’ command to delete this topic.
Then add a final closing quote.
Then route it to a file for later execution.

1 Like