I recently asked nearly the same question (see my post “Marginal line numbers extracted from text” at the top of the forum).
Jongware replied with this nifty script he wrote that does the trick for me. Be sure to make all of the quote marks straight quotes (retype them so they look straight). And you’ll need to paste in your grep expression in line 2 to replace mine: “[d+]”;
Keep the quotes and the final semicolon, my grep expression starts with the first slash and ends with the close bracket.
once done, the anchored boxes weren’t quite in the right position, so I searched for all anchored boxes (using “object” in the find menu) with custom positioning, and changed to an object style I had created that positioned them 12 pts into the outside margin, base aligned with the anchor point. If I knew java, I could probably finesse the script to do that as well, but it was easy enough as a separate search.
good luck!
app.findGrepPreferences = null;
app.findGrepPreferences.findWhat = ?[d+]?;
numberList = app.activeDocument.findGrep(true);
for (i=0; i<numberList.length; i++)
{
tf = numberList[i].textFrames.add({anchoredObjectSettings:{anchoredPosition:AnchorPosition.ANCHORED, anchorXoffset:?1mm?}});
tf.geometricBounds = [“0mm”,”0mm”,”10mm”, “50mm” ];
numberList[i].move(LocationOptions.AT_BEGINNING, tf.texts[0]);
tf.fit (FitOptions.FRAME_TO_CONTENT);
}