I'm putting all the firewall rules into a text file named firewall.rsc that I edit on my laptop, then upload it to my MT switch/router, and there I just use the command "/import firewall.rsc".
BUT: the import does an append to the currently existing rules list.
So, before importing I have to clear the whole list (except the built-in rule 0, which cannot be deleted).
Of ccourse I have first to check how many rules are in the old list, to pass that number to the above script/batch command that I use in the CLI directly, ie. not from a script...
Ie.: There are many roads to Rome, or: There's more than one way to skin a cat
You have defined yourself as an expert programmer, I would have expected a better logical analysis in an attempt to solve the problem,
such as putting the deletion of all the rules and immediately add the indispensable firewall rule and then all the others, directly inside the firewall.rsc file...
Probably you use 7 beta, is the wrong forum section, all non-beta are for 6.x only
But,
for example, set a comment on rule(s) like "KEEP this rule becaue...." and remove all not have uppercase KEEP in any part of the comment...
Can have on this way multiple KEEP rules on any position...
/ip firewall filter
remove [find where (!(comment~"KEEP"))]
you also can add the code on top of your firewall.rsc