SED GURUS - Help!

I wish to substituite a string on each line but ONLY if it appears within double-quotes:

this_string="abc#def#geh" # Comment here

I wish to change the "#" characters within the double quoted string to "_":

this_string="abc_def_geh" # Comment here

... but as you see, the "comment" hash is retained.

The substitution cannot check positional placement, only whether it is within quotes.

Any ideas?

Cheers

I could not think of a straight forward approach. Assuming --- does not occur anywhere in the line.

sed -e "s/\(.*\)#\([^#]*\)/\1---\2/;s/#/_/g;s/---/#/" input.txt

I have changed the last '#' to '---', replaced the other '#' with '_', and reverted back '---' to '#'.

Does it have to be strictly sed ?

This awk solution seems to work just ok

echo 'this_string="abc#def#geh" # Comment here' | awk -F'"' '{ gsub("#","_",$2); print sprintf("%s\"%s\"%s",$1,$2,$3) }'