The underlying problem is that sam is simply not line-oriented. If you're doing things with a file which is naturally thought of a series of lines then ed is usually better than sam -d.
-- John Stalker School of Mathematics Trinity College Dublin tel +353 1 896 1983 fax +353 1 896 2282