I am trying to use sed to replace all instances of a command with a variable, expect when they come after a comment or is part of another word. I have gotten close, being able to replace one instance before a comment, but not if there is more than one. 

I have a test file with the line:
`rm rm # rm`

I want to make this read:
`$RM $RM # rm`

This is what I have so far:
`sed -i 's/\(^\|[^[#.*]]\)\brm\b/\1$RM/' file1`

Which returns:
`$RM rm # rm`

Any help is much appreciated. Other solutions not involving sed are welcome, but I might need some help understanding them.

Thanks!

EDIT:

This is just an example of what I am looking for. Not every line will be formatted like this, and not every line will contain a command before the comment, or vise versa. I am just looking for a solution that will also cover a situation similar to this example. Sorry for the lack of explanation. Here is a slightly better example:

```
   "$#"    #rm
#  rm
rm   #  rm
  rm
"rm  "
'rm  '
`rm  `
{rm  }
$#  rm  # rm
rm rm # rm
rm # rm rm
rmremovermlink

```

Output should be: 

```
  "$#"    #rm
#  rm
$RM   #  rm
  $RM
"$RM  "
'$RM  '
`$RM  `
{$RM  }
$#  $RM  # rm
$RM $RM # rm
$RM # rm rm
rmremovermlink

```