regex - Using sed to replace multiple instances in the same line before a comment -


i trying use sed replace instances of command variable, expect when come after comment or part of word. have gotten close, being able replace 1 instance before comment, not if there more one.

i have test file line: rm rm # rm

i want make read: $rm $rm # rm

this have far: sed -i 's/\(^\|[^[#.*]]\)\brm\b/\1$rm/' file1

which returns: $rm rm # rm

any appreciated. other solutions not involving sed welcome, might need understanding them.

thanks!

edit:

this example of looking for. not every line formatted this, , not every line contain command before comment, or vise versa. looking solution cover situation similar example. sorry lack of explanation. here 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 

you can use perl command substitution:

perl -pe 's/(?<!\$)#.*$(*skip)(*f)|\brm\b/\$rm/g' file    "$#"    #rm #  rm $rm   #  rm   $rm "$rm  " '$rm  ' `$rm  ` {$rm  } $#  $rm  # rm $rm $rm # rm $rm # rm rm rmremovermlink 

regex demo


Comments