@Oddela – there already should be some script snippets doing this (more or less). The methods identifying the right text ranges might vary a bit. Some work with special strings before and after the text as identifier, some work with footnotes as identifier, some work with character styles, some with paragraph styles. Some would do it, if you exchange your own names for paragraph styles, character styles and object styles. That means: You have to read the code and understand where to change parameters for your special needs.
Here one example by Kai Rübsamen on hilfdirselbst.ch that is using special content strings as identifiers for the text, that define exactly what should go into the anchored text frame and what should not:
Texte automatisiert in Marginalien ändern
There are many more examples out in the web…