There are as many ways to Rome that there is opinons about sed.
Well, I’d first say that Nigels solution, is the fastest, in comparison to awk, but when speed really matters, awk may in many situations relieve you of forking subshell after subshell to execute commands in, and thereby end up faster. Since you can do so much with it!
Here is my take, which is different, because I use the tools that are easier to use. I use tr and echo to create the final result.
set t to quoted form of "I begin the essay with a thought
abc 123 xyz
about the end of the story.
123 def"
set cmd to "a=$(echo " & t & " | sed -n '/123/ =') ; echo $a |tr ' ' ',' "
(do shell script cmd)
”> "2,4"
Here is another variation, that uses nl for line numbering.
set t to quoted form of "I begin the essay with a thought
abc 123 xyz
about the end of the story.
123 def"
set cmd to "a=$(echo " & t & " |nl -b a |sed -nE '/123/ s/^( *)([[:digit:]]+)(.*)/\\2/p') ; echo $a |tr ' ' ',' "
(do shell script cmd)
Here is a more pure sed version, that I believe only will work with a pair of matches.
set t to quoted form of "I begin the essay with a thought
abc 123 xyz
about the end of the story.
123 def"
set cmd to "echo " & t & " |nl -b a |sed -nEe '/123/ s/^[^0-9]+([0-9]+).*/\\1/p' | sed -e 'N' -ne 's/\\n/,/p'"
(do shell script cmd)
A final variation, before I finally get buried into the boring book again!
I have tried to make it as easy as possible, and reducing the number of system calls (exec), I don’t think it comes close to speed with Nigel’s, but it is far easier to write on the fly! (Unless you are Nigel. ).
set t to quoted form of "I begin the essay with a thought
abc 123 xyz
about the end of the story.
123 def"
set cmd to " echo $(grep -n 123 <<<" & t & " |sed -n 's/\\([0-9]*\\):.*/\\1/p') |tr ' ' ','"
(do shell script cmd)
What can I say, it’s a boring day!