Applescript to replace string using sed
Solution 1: sed

Option -r of GNU sed is -E on the OS X/BSD sed (the one that comes with the OS, /usr/bin/sed). And to get rid of the encoding problem with 's, add export LC_ALL=en_US.UTF-8; export LANG=en_US.UTF-8; to the beginning of the do shell script command (see the question here):

set original_text to "string  string  string  $  text1
string  string  string  $  text2
text3
string  string  string  $  text4"

set commandString to "export LC_ALL=en_US.UTF-8; export LANG=en_US.UTF-8; " &amp; ¬
    "echo " &amp; quoted form of original_text &amp; " | sed -E 's|^(.*)\\$ ?(.) (.*)$|$ \\3|g'" as string
set formattedCode to do shell script commandString


Returns:

$ text1
$ text2
text3
$ text4




Solution 2: AppleScript's text item delimiters

set original_text to "string  string  string  $  text1
string  string  string  $  text2
text3
string  string  string  $  text4"

set output to {}
set od to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"
"}
set all_lines to every text item of original_text
repeat with the_line in all_lines
    if "$" is not in the_line then
        set output to output &amp; the_line
    else
        set AppleScript's text item delimiters to {"$"}
        set latter_part to last text item of the_line
        set AppleScript's text item delimiters to {" "}
        set last_word to last text item of latter_part
        set output to output &amp; ("$ " &amp; last_word as string)
    end if
end repeat
set AppleScript's text item delimiters to {"
"}
set output to output as string
set AppleScript's text item delimiters to od
return output


Returns:

$ text1
$ text2
text3
$ text4