in reply to command line replace incorrectly indexes $.

It seems to me that there's a lot you're not telling us. You'd get better help if you posted your input file (trimmed down, if necessary).